<!DOCTYPE html><html><head><meta charset="utf-8"><title>Angular - HttpClient</title><base href="/"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="search" type="application/opensearchdescription+xml" href="assets/opensearch.xml"><link rel="icon" type="image/x-icon" href="assets/images/favicons/favicon.ico"><link rel="icon" type="image/png" href="assets/images/favicons/favicon-32x32.png" sizes="32x32"><link rel="icon" type="image/png" href="assets/images/favicons/favicon-194x194.png" sizes="194x194"><link rel="icon" type="image/png" href="assets/images/favicons/favicon-96x96.png" sizes="96x96"><link rel="icon" type="image/png" href="assets/images/favicons/favicon-16x16.png" sizes="16x16"><link rel="apple-touch-icon" sizes="144x144" href="assets/images/favicons/favicon-144x144.png"><link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/images/favicons/favicon-144x144.png"><link href="assets/fonts/Material_Icons.css" rel="stylesheet"><link href="assets/fonts/Droid_Sans_Mono.css" rel="stylesheet"><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"><link rel="manifest" href="pwa-manifest.json"><meta name="theme-color" content="#1976d2"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="translucent"><script async="" src="assets/js/analytics.js"></script><script>!function(e,a,n,t,s,c,g){e.GoogleAnalyticsObject=s,e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,c=a.createElement(n),g=a.getElementsByTagName(n)[0],c.async=1,c.src="assets/js/analytics.js",~e.name.indexOf("NG_DEFER_BOOTSTRAP")||g.parentNode.insertBefore(c,g)}(window,document,"script",0,"ga")</script><script>window.onerror=function(){ga("send","exception",{exDescription:function(e,r,n,a,c){var l;e=e.replace(/^Error: /,""),l=c?c.stack.replace(/^Error: /,"").replace(e+"\n","").replace(/^ +/gm,"").replace(/^at /gm,"").replace(/(?: \(|@)http.+\/([^/)]+)\)?(?:\n|$)/gm,"@$1\n").replace(/ *\(eval code(:\d+:\d+)\)(?:\n|$)/gm,"@???$1\n"):r+":"+(n=n||"?")+":"+(a=a||"?");return(e+"\n"+l).substr(0,150)}.apply(null,arguments),exFatal:!0})}</script><script nomodule="" src="generated/ie-polyfills.min.js"></script><link rel="stylesheet" href="styles.10ba6936decaea45eabb.css"><style>@media screen and (-ms-high-contrast:active){.mat-toolbar{outline:solid 1px}}.mat-toolbar-row,.mat-toolbar-single-row{display:flex;box-sizing:border-box;padding:0 16px;width:100%;flex-direction:row;align-items:center;white-space:nowrap}.mat-toolbar-multiple-rows{display:flex;box-sizing:border-box;flex-direction:column;width:100%}.mat-toolbar-multiple-rows{min-height:64px}.mat-toolbar-row,.mat-toolbar-single-row{height:64px}@media (max-width:599px){.mat-toolbar-multiple-rows{min-height:56px}.mat-toolbar-row,.mat-toolbar-single-row{height:56px}}</style><style>.mat-icon{background-repeat:no-repeat;display:inline-block;fill:currentColor;height:24px;width:24px}.mat-icon.mat-icon-inline{font-size:inherit;height:inherit;line-height:inherit;width:inherit}[dir=rtl] .mat-icon-rtl-mirror{transform:scale(-1,1)}.mat-form-field:not(.mat-form-field-appearance-legacy) .mat-form-field-prefix .mat-icon,.mat-form-field:not(.mat-form-field-appearance-legacy) .mat-form-field-suffix .mat-icon{display:block}.mat-form-field:not(.mat-form-field-appearance-legacy) .mat-form-field-prefix .mat-icon-button .mat-icon,.mat-form-field:not(.mat-form-field-appearance-legacy) .mat-form-field-suffix .mat-icon-button .mat-icon{margin:auto}</style><style>.mat-button .mat-button-focus-overlay,.mat-icon-button .mat-button-focus-overlay{opacity:0}.mat-button:hover .mat-button-focus-overlay,.mat-stroked-button:hover .mat-button-focus-overlay{opacity:.04}@media (hover:none){.mat-button:hover .mat-button-focus-overlay,.mat-stroked-button:hover .mat-button-focus-overlay{opacity:0}}.mat-button,.mat-flat-button,.mat-icon-button,.mat-stroked-button{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:64px;line-height:36px;padding:0 16px;border-radius:4px;overflow:visible}.mat-button::-moz-focus-inner,.mat-flat-button::-moz-focus-inner,.mat-icon-button::-moz-focus-inner,.mat-stroked-button::-moz-focus-inner{border:0}.mat-button[disabled],.mat-flat-button[disabled],.mat-icon-button[disabled],.mat-stroked-button[disabled]{cursor:default}.mat-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-button.cdk-program-focused .mat-button-focus-overlay,.mat-flat-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-flat-button.cdk-program-focused .mat-button-focus-overlay,.mat-icon-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-icon-button.cdk-program-focused .mat-button-focus-overlay,.mat-stroked-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-stroked-button.cdk-program-focused .mat-button-focus-overlay{opacity:.12}.mat-button::-moz-focus-inner,.mat-flat-button::-moz-focus-inner,.mat-icon-button::-moz-focus-inner,.mat-stroked-button::-moz-focus-inner{border:0}.mat-raised-button{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:64px;line-height:36px;padding:0 16px;border-radius:4px;overflow:visible;transform:translate3d(0,0,0);transition:background .4s cubic-bezier(.25,.8,.25,1),box-shadow 280ms cubic-bezier(.4,0,.2,1)}.mat-raised-button::-moz-focus-inner{border:0}.mat-raised-button[disabled]{cursor:default}.mat-raised-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-raised-button.cdk-program-focused .mat-button-focus-overlay{opacity:.12}.mat-raised-button::-moz-focus-inner{border:0}._mat-animation-noopable.mat-raised-button{transition:none;animation:none}.mat-stroked-button{border:1px solid currentColor;padding:0 15px;line-height:34px}.mat-fab{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:64px;line-height:36px;padding:0 16px;border-radius:4px;overflow:visible;transform:translate3d(0,0,0);transition:background .4s cubic-bezier(.25,.8,.25,1),box-shadow 280ms cubic-bezier(.4,0,.2,1);min-width:0;border-radius:50%;width:56px;height:56px;padding:0;flex-shrink:0}.mat-fab::-moz-focus-inner{border:0}.mat-fab[disabled]{cursor:default}.mat-fab.cdk-keyboard-focused .mat-button-focus-overlay,.mat-fab.cdk-program-focused .mat-button-focus-overlay{opacity:.12}.mat-fab::-moz-focus-inner{border:0}._mat-animation-noopable.mat-fab{transition:none;animation:none}.mat-fab .mat-button-wrapper{padding:16px 0;display:inline-block;line-height:24px}.mat-mini-fab{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:64px;line-height:36px;padding:0 16px;border-radius:4px;overflow:visible;transform:translate3d(0,0,0);transition:background .4s cubic-bezier(.25,.8,.25,1),box-shadow 280ms cubic-bezier(.4,0,.2,1);min-width:0;border-radius:50%;width:40px;height:40px;padding:0;flex-shrink:0}.mat-mini-fab::-moz-focus-inner{border:0}.mat-mini-fab[disabled]{cursor:default}.mat-mini-fab.cdk-keyboard-focused .mat-button-focus-overlay,.mat-mini-fab.cdk-program-focused .mat-button-focus-overlay{opacity:.12}.mat-mini-fab::-moz-focus-inner{border:0}._mat-animation-noopable.mat-mini-fab{transition:none;animation:none}.mat-mini-fab .mat-button-wrapper{padding:8px 0;display:inline-block;line-height:24px}.mat-icon-button{padding:0;min-width:0;width:40px;height:40px;flex-shrink:0;line-height:40px;border-radius:50%}.mat-icon-button .mat-icon,.mat-icon-button i{line-height:24px}.mat-button-focus-overlay,.mat-button-ripple.mat-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none;border-radius:inherit}.mat-button-focus-overlay{border-radius:inherit;opacity:0;transition:opacity .2s cubic-bezier(.35,0,.25,1),background-color .2s cubic-bezier(.35,0,.25,1)}._mat-animation-noopable .mat-button-focus-overlay{transition:none}@media screen and (-ms-high-contrast:active){.mat-button-focus-overlay{background-color:rgba(255,255,255,.5)}}.mat-button-ripple-round{border-radius:50%;z-index:1}.mat-button .mat-button-wrapper>*,.mat-fab .mat-button-wrapper>*,.mat-flat-button .mat-button-wrapper>*,.mat-icon-button .mat-button-wrapper>*,.mat-mini-fab .mat-button-wrapper>*,.mat-raised-button .mat-button-wrapper>*,.mat-stroked-button .mat-button-wrapper>*{vertical-align:middle}.mat-form-field:not(.mat-form-field-appearance-legacy) .mat-form-field-prefix .mat-icon-button,.mat-form-field:not(.mat-form-field-appearance-legacy) .mat-form-field-suffix .mat-icon-button{display:block;font-size:inherit;width:2.5em;height:2.5em}@media screen and (-ms-high-contrast:active){.mat-button,.mat-fab,.mat-flat-button,.mat-icon-button,.mat-mini-fab,.mat-raised-button{outline:solid 1px}}</style><style>.mat-drawer-container{position:relative;z-index:1;box-sizing:border-box;-webkit-overflow-scrolling:touch;display:block;overflow:hidden}.mat-drawer-container[fullscreen]{top:0;left:0;right:0;bottom:0;position:absolute}.mat-drawer-container[fullscreen].mat-drawer-opened{overflow:hidden}.mat-drawer-container.mat-drawer-container-explicit-backdrop .mat-drawer-side{z-index:3}.mat-drawer-container.ng-animate-disabled .mat-drawer-backdrop,.mat-drawer-container.ng-animate-disabled .mat-drawer-content,.ng-animate-disabled .mat-drawer-container .mat-drawer-backdrop,.ng-animate-disabled .mat-drawer-container .mat-drawer-content{transition:none}.mat-drawer-backdrop{top:0;left:0;right:0;bottom:0;position:absolute;display:block;z-index:3;visibility:hidden}.mat-drawer-backdrop.mat-drawer-shown{visibility:visible}.mat-drawer-transition .mat-drawer-backdrop{transition-duration:.4s;transition-timing-function:cubic-bezier(.25,.8,.25,1);transition-property:background-color,visibility}@media screen and (-ms-high-contrast:active){.mat-drawer-backdrop{opacity:.5}}.mat-drawer-content{position:relative;z-index:1;display:block;height:100%;overflow:auto}.mat-drawer-transition .mat-drawer-content{transition-duration:.4s;transition-timing-function:cubic-bezier(.25,.8,.25,1);transition-property:transform,margin-left,margin-right}.mat-drawer{position:relative;z-index:4;display:block;position:absolute;top:0;bottom:0;z-index:3;outline:0;box-sizing:border-box;overflow-y:auto;transform:translate3d(-100%,0,0)}@media screen and (-ms-high-contrast:active){.mat-drawer,[dir=rtl] .mat-drawer.mat-drawer-end{border-right:solid 1px currentColor}}@media screen and (-ms-high-contrast:active){.mat-drawer.mat-drawer-end,[dir=rtl] .mat-drawer{border-left:solid 1px currentColor;border-right:none}}.mat-drawer.mat-drawer-side{z-index:2}.mat-drawer.mat-drawer-end{right:0;transform:translate3d(100%,0,0)}[dir=rtl] .mat-drawer{transform:translate3d(100%,0,0)}[dir=rtl] .mat-drawer.mat-drawer-end{left:0;right:auto;transform:translate3d(-100%,0,0)}.mat-drawer-inner-container{width:100%;height:100%;overflow:auto;-webkit-overflow-scrolling:touch}.mat-sidenav-fixed{position:fixed}</style><style>.nav-link.highlight[_ngcontent-c5]{color:#ff0}</style><style>.mat-progress-bar{display:block;height:4px;overflow:hidden;position:relative;transition:opacity 250ms linear;width:100%}._mat-animation-noopable.mat-progress-bar{transition:none;animation:none}.mat-progress-bar .mat-progress-bar-element,.mat-progress-bar .mat-progress-bar-fill::after{height:100%;position:absolute;width:100%}.mat-progress-bar .mat-progress-bar-background{width:calc(100% + 10px)}@media screen and (-ms-high-contrast:active){.mat-progress-bar .mat-progress-bar-background{display:none}}.mat-progress-bar .mat-progress-bar-buffer{transform-origin:top left;transition:transform 250ms ease}@media screen and (-ms-high-contrast:active){.mat-progress-bar .mat-progress-bar-buffer{border-top:solid 5px;opacity:.5}}.mat-progress-bar .mat-progress-bar-secondary{display:none}.mat-progress-bar .mat-progress-bar-fill{animation:none;transform-origin:top left;transition:transform 250ms ease}@media screen and (-ms-high-contrast:active){.mat-progress-bar .mat-progress-bar-fill{border-top:solid 4px}}.mat-progress-bar .mat-progress-bar-fill::after{animation:none;content:'';display:inline-block;left:0}.mat-progress-bar[dir=rtl],[dir=rtl] .mat-progress-bar{transform:rotateY(180deg)}.mat-progress-bar[mode=query]{transform:rotateZ(180deg)}.mat-progress-bar[mode=query][dir=rtl],[dir=rtl] .mat-progress-bar[mode=query]{transform:rotateZ(180deg) rotateY(180deg)}.mat-progress-bar[mode=indeterminate] .mat-progress-bar-fill,.mat-progress-bar[mode=query] .mat-progress-bar-fill{transition:none}.mat-progress-bar[mode=indeterminate] .mat-progress-bar-primary,.mat-progress-bar[mode=query] .mat-progress-bar-primary{-webkit-backface-visibility:hidden;backface-visibility:hidden;animation:mat-progress-bar-primary-indeterminate-translate 2s infinite linear;left:-145.166611%}.mat-progress-bar[mode=indeterminate] .mat-progress-bar-primary.mat-progress-bar-fill::after,.mat-progress-bar[mode=query] .mat-progress-bar-primary.mat-progress-bar-fill::after{-webkit-backface-visibility:hidden;backface-visibility:hidden;animation:mat-progress-bar-primary-indeterminate-scale 2s infinite linear}.mat-progress-bar[mode=indeterminate] .mat-progress-bar-secondary,.mat-progress-bar[mode=query] .mat-progress-bar-secondary{-webkit-backface-visibility:hidden;backface-visibility:hidden;animation:mat-progress-bar-secondary-indeterminate-translate 2s infinite linear;left:-54.888891%;display:block}.mat-progress-bar[mode=indeterminate] .mat-progress-bar-secondary.mat-progress-bar-fill::after,.mat-progress-bar[mode=query] .mat-progress-bar-secondary.mat-progress-bar-fill::after{-webkit-backface-visibility:hidden;backface-visibility:hidden;animation:mat-progress-bar-secondary-indeterminate-scale 2s infinite linear}.mat-progress-bar[mode=buffer] .mat-progress-bar-background{-webkit-backface-visibility:hidden;backface-visibility:hidden;animation:mat-progress-bar-background-scroll 250ms infinite linear;display:block}.mat-progress-bar._mat-animation-noopable .mat-progress-bar-background,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-buffer,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-fill,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-fill::after,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-primary,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-primary.mat-progress-bar-fill::after,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-secondary,.mat-progress-bar._mat-animation-noopable .mat-progress-bar-secondary.mat-progress-bar-fill::after{animation:none;transition:none}@keyframes mat-progress-bar-primary-indeterminate-translate{0%{transform:translateX(0)}20%{animation-timing-function:cubic-bezier(.5,0,.70173,.49582);transform:translateX(0)}59.15%{animation-timing-function:cubic-bezier(.30244,.38135,.55,.95635);transform:translateX(83.67142%)}100%{transform:translateX(200.61106%)}}@keyframes mat-progress-bar-primary-indeterminate-scale{0%{transform:scaleX(.08)}36.65%{animation-timing-function:cubic-bezier(.33473,.12482,.78584,1);transform:scaleX(.08)}69.15%{animation-timing-function:cubic-bezier(.06,.11,.6,1);transform:scaleX(.66148)}100%{transform:scaleX(.08)}}@keyframes mat-progress-bar-secondary-indeterminate-translate{0%{animation-timing-function:cubic-bezier(.15,0,.51506,.40969);transform:translateX(0)}25%{animation-timing-function:cubic-bezier(.31033,.28406,.8,.73371);transform:translateX(37.65191%)}48.35%{animation-timing-function:cubic-bezier(.4,.62704,.6,.90203);transform:translateX(84.38617%)}100%{transform:translateX(160.27778%)}}@keyframes mat-progress-bar-secondary-indeterminate-scale{0%{animation-timing-function:cubic-bezier(.15,0,.51506,.40969);transform:scaleX(.08)}19.15%{animation-timing-function:cubic-bezier(.31033,.28406,.8,.73371);transform:scaleX(.4571)}44.15%{animation-timing-function:cubic-bezier(.4,.62704,.6,.90203);transform:scaleX(.72796)}100%{transform:scaleX(.08)}}@keyframes mat-progress-bar-background-scroll{to{transform:translateX(-8px)}}</style><script charset="utf-8" src="toc-toc-module-ngfactory.36694c537d7ff0b2c081.js"></script><script charset="utf-8" src="default~code-code-example-module-ngfactory~code-code-tabs-module-ngfactory~getting-started-ng-for-ng~82f414e5.c64b8abba8f3b7168616.js"></script><script charset="utf-8" src="default~code-code-example-module-ngfactory~code-code-tabs-module-ngfactory.98830c4eaea3268880de.js"></script><script charset="utf-8" src="code-code-example-module-ngfactory.bb14a03c7095ffd0e7bd.js"></script><script charset="utf-8" src="live-example-live-example-module-ngfactory.fef451c7b16613f97732.js"></script><script charset="utf-8" src="21.d3ebf64aa7b6d3a4b8f6.js"></script></head><body><aio-shell ng-version="7.0.0" class="mode-stable sidenav-open page-guide-http folder-guide view-SideNav aio-notification-show"><div id="top-of-page"></div><mat-toolbar class="app-toolbar no-print mat-toolbar mat-primary mat-toolbar-multiple-rows" color="primary"><mat-toolbar-row class="notification-container mat-toolbar-row"><aio-notification expirationdate="2019-03-01" notificationid="survey-february-2019" class="ng-tns-c2-0 ng-trigger ng-trigger-hideAnimation"><span class="content"><a href="http://bit.ly/angular-survey-2019" target="_blank"><mat-icon aria-label="Announcement" class="icon mat-icon" role="img" svgicon="insert_comment" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M20 2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"></path><path d="M0 0h24v24H0z" fill="none"></path></svg></mat-icon><span class="message"><b>填写这份《一分钟调查》</b>，帮我们（开发组）做得更好！</span><span class="action-button">去填写</span></a></span><button class="close-button mat-icon-button" aria-label="Close" mat-icon-button=""><span class="mat-button-wrapper"><mat-icon aria-label="Dismiss notification" class="mat-icon ng-tns-c2-0" role="img" svgicon="close" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"></path><path d="M0 0h24v24H0z" fill="none"></path></svg></mat-icon></span><div class="mat-button-ripple mat-ripple mat-button-ripple-round" matripple=""></div><div class="mat-button-focus-overlay"></div></button></aio-notification></mat-toolbar-row><mat-toolbar-row class="mat-toolbar-row"><button class="hamburger mat-button" mat-button="" title="Docs menu"><span class="mat-button-wrapper"><mat-icon class="mat-icon" role="img" svgicon="menu" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"></path></svg></mat-icon></span><div class="mat-button-ripple mat-ripple" matripple=""></div><div class="mat-button-focus-overlay"></div></button><a class="nav-link home" href="/"><img alt="Home" height="40" src="assets/images/logos/angular/logo-nav@2x.png" title="Home" width="150" class="ng-star-inserted"></a><aio-top-menu _nghost-c5="" class="ng-star-inserted"><ul _ngcontent-c5="" role="navigation"><li _ngcontent-c5="" class="ng-star-inserted"><a _ngcontent-c5="" class="nav-link" href="features" title="特性"><span _ngcontent-c5="" class="nav-link-inner">特性</span></a></li><li _ngcontent-c5="" class="ng-star-inserted"><a _ngcontent-c5="" class="nav-link" href="docs" title="文档"><span _ngcontent-c5="" class="nav-link-inner">文档</span></a></li><li _ngcontent-c5="" class="ng-star-inserted"><a _ngcontent-c5="" class="nav-link" href="resources" title="资源"><span _ngcontent-c5="" class="nav-link-inner">资源</span></a></li><li _ngcontent-c5="" class="ng-star-inserted"><a _ngcontent-c5="" class="nav-link" href="events" title="会议"><span _ngcontent-c5="" class="nav-link-inner">会议</span></a></li><li _ngcontent-c5="" class="ng-star-inserted"><a _ngcontent-c5="" class="nav-link" href="https://blog.angular.io/" title="博客"><span _ngcontent-c5="" class="nav-link-inner">博客</span></a></li><li _ngcontent-c5="" class="ng-star-inserted"><a _ngcontent-c5="" class="nav-link" href="translations/cn/home" title="关于中文版"><span _ngcontent-c5="" class="nav-link-inner">关于中文版</span></a></li></ul></aio-top-menu><aio-search-box class="search-container"><input aria-label="search" placeholder="搜索" type="search"></aio-search-box><div class="toolbar-external-icons-container"><a aria-label="Angular on twitter" href="https://twitter.com/angular" title="Twitter"><mat-icon class="mat-icon" role="img" svgicon="logos:twitter" aria-hidden="true"><svg focusable="false" viewBox="0 0 50 59" xmlns="http://www.w3.org/2000/svg"><path d="M50,9.3c-1.8,0.8-3.8,1.4-5.9,1.6c2.1-1.3,3.7-3.3,4.5-5.7c-2,1.2-4.2,2-6.5,2.5c-1.9-2-4.5-3.2-7.5-3.2c-5.7,0-10.3,4.6-10.3,10.3c0,0.8,0.1,1.6,0.3,2.3C16.1,16.7,8.5,12.6,3.5,6.4c-0.9,1.5-1.4,3.3-1.4,5.2c0,3.6,1.8,6.7,4.6,8.5C5,20,3.4,19.6,2,18.8c0,0,0,0.1,0,0.1c0,5,3.5,9.1,8.2,10.1c-0.9,0.2-1.8,0.4-2.7,0.4c-0.7,0-1.3-0.1-1.9-0.2c1.3,4.1,5.1,7,9.6,7.1c-3.5,2.8-7.9,4.4-12.7,4.4c-0.8,0-1.6,0-2.4-0.1c4.5,2.9,9.9,4.6,15.7,4.6c18.9,0,29.2-15.6,29.2-29.2c0-0.4,0-0.9,0-1.3C46.9,13.2,48.6,11.4,50,9.3z"></path></svg></mat-icon></a><a aria-label="Angular on github" href="https://github.com/angular/angular" title="GitHub"><mat-icon class="mat-icon" role="img" svgicon="logos:github" aria-hidden="true"><svg focusable="false" viewBox="0 0 51.8 50.4" xmlns="http://www.w3.org/2000/svg"><path d="M25.9,0.2C11.8,0.2,0.3,11.7,0.3,25.8c0,11.3,7.3,20.9,17.5,24.3c1.3,0.2,1.7-0.6,1.7-1.2c0-0.6,0-2.6,0-4.8c-7.1,1.5-8.6-3-8.6-3c-1.2-3-2.8-3.7-2.8-3.7c-2.3-1.6,0.2-1.6,0.2-1.6c2.6,0.2,3.9,2.6,3.9,2.6c2.3,3.9,6,2.8,7.5,2.1c0.2-1.7,0.9-2.8,1.6-3.4c-5.7-0.6-11.7-2.8-11.7-12.7c0-2.8,1-5.1,2.6-6.9c-0.3-0.7-1.1-3.3,0.3-6.8c0,0,2.1-0.7,7,2.6c2-0.6,4.2-0.9,6.4-0.9c2.2,0,4.4,0.3,6.4,0.9c4.9-3.3,7-2.6,7-2.6c1.4,3.5,0.5,6.1,0.3,6.8c1.6,1.8,2.6,4.1,2.6,6.9c0,9.8-6,12-11.7,12.6c0.9,0.8,1.7,2.4,1.7,4.7c0,3.4,0,6.2,0,7c0,0.7,0.5,1.5,1.8,1.2c10.2-3.4,17.5-13,17.5-24.3C51.5,11.7,40.1,0.2,25.9,0.2z"></path></svg></mat-icon></a></div></mat-toolbar-row></mat-toolbar><mat-sidenav-container class="sidenav-container mat-drawer-container mat-sidenav-container mat-drawer-transition has-floating-toc" role="main"><div class="mat-drawer-backdrop ng-star-inserted"></div><div class="cdk-visually-hidden cdk-focus-trap-anchor"></div><mat-sidenav class="sidenav mat-drawer mat-sidenav ng-tns-c7-1 ng-trigger ng-trigger-transform mat-drawer-side ng-star-inserted" tabindex="-1" style="transform:none;visibility:visible"><div class="mat-drawer-inner-container"><aio-nav-menu><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="guide/quickstart" title="对 Angular 和 Angular CLI 基础知识的简短介绍" target="_self">快速上手</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-1 collapsed ng-star-inserted" type="button" title="此《英雄指南》教程会带你用 TypeScript 一步步创建一个 Angular 应用。" aria-pressed="false">教程<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="tutorial" title="《英雄指南》教程简介" target="_self">简介</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt0" title="创建应用的外壳" target="_self">应用的“外壳”</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt1" title="第一部分：构建一个简单的英雄编辑器" target="_self">1. 英雄编辑器</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt2" title="第二部分：构建一个主从结构的页面，用于展现英雄列表。" target="_self">2. 显示英雄列表</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt3" title="第三部分：把主从结构的页面重构成多个组件。" target="_self">3. 主从组件</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt4" title="第四部分：创建一个可复用的服务来管理英雄数据。" target="_self">4. 服务</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt5" title="第五部分：添加 Angular 路由器，并且学习在视图之间导航。" target="_self">5. 路由</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="tutorial/toh-pt6" title="第六部分：通过 HTTP 来获取并保存英雄数据。" target="_self">6. HTTP</a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-1 expanded selected ng-star-inserted" type="button" title="学习 Angular 的核心知识" aria-pressed="true">核心知识<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 expanded selected"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-2 collapsed ng-star-inserted" type="button" title="Angular 应用的基本构造块。" aria-pressed="false">架构<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/architecture" title="Angular 应用的基本构造块" target="_self">架构概览</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/architecture-modules" title="关于模块。" target="_self">模块（NgModule）简介</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/architecture-components" title="关于组件、模板和视图。" target="_self">组件简介</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/architecture-services" title="关于服务与依赖注入。" target="_self">服务与 DI 简介</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/architecture-next-steps" title="学完基础知识之后……" target="_self">后续步骤</a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-2 collapsed ng-star-inserted" type="button" title="使用数据绑定构建动态视图" aria-pressed="false">组件与模板<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/displaying-data" title="属性绑定可以帮助应用把数据显示在界面上" target="_self">显示数据</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/template-syntax" title="学习如何写模板，以便借助数据绑定机制显示数据并响应事件。" target="_self">模板语法</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/user-input" title="用户输入会触发 DOM 事件。Angular 会通过事件绑定来监听那些事件，并把修改后的值传回应用的组件和模型中。" target="_self">用户输入</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/lifecycle-hooks" title="Angular 调用指令和组件的生命周期钩子函数，包括它的创建、变更和销毁时。" target="_self">生命周期钩子</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/component-interaction" title="在不同的指令和组件之间共享信息" target="_self">组件交互</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/component-styles" title="添加专属于某个组件的样式" target="_self">组件样式</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/elements" title="把组件转换成自定义元素。" target="_self">Angular 自定义元素</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/dynamic-component-loader" title="动态加载组件" target="_self">动态组件</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/attribute-directives" title="属性型指令把行为添加到现有元素上。" target="_self">属性型指令</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/structural-directives" title="结构型指令可以操纵页面的布局" target="_self">结构型指令</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/pipes" title="管道可以在模板中转换显示的内容。" target="_self">管道</a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-2 collapsed ng-star-inserted" type="button" title="Angular 的表单" aria-pressed="false">表单<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/forms-overview" title="表单可以创建集中、高效、引人注目的输入体验。Angular 表单可以协调一组数据绑定控件，跟踪变更，验证输入，并表达错误信息。" target="_self">简介</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/reactive-forms" title="使用 FormBuilder、表单组和表单数组创建响应式表单。" target="_self">响应式表单</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/forms" title="使用指令和 Angular 模板语法创建模板驱动表单。" target="_self">模板驱动表单</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/form-validation" title="验证用户的表单输入" target="_self">表单验证</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/dynamic-form" title="使用 FormGroup 渲染动态表单。" target="_self">动态表单</a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-2 collapsed ng-star-inserted" type="button" title="Observable 与 RxJS" aria-pressed="false">Observable 与 RxJS<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/observables" title="" target="_self">可观察对象(Observable)</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/rx-library" title="" target="_self">RxJS 库</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/observables-in-angular" title="" target="_self">Angular 中的可观察对象</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/practical-observable-usage" title="" target="_self">用法实战</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/comparing-observables" title="" target="_self">与其它技术的比较</a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/bootstrapping" title="在应用的根模块（AppModule）中告诉 Angular 如何构造并引导引用。" target="_self">引导启动</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-2 collapsed ng-star-inserted" type="button" title="Angular 中的模块" aria-pressed="false">NgModule<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/ngmodules" title="使用 NgModule 让你的应用更高效" target="_self">NgModule 简介</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/ngmodule-vs-jsmodule" title="JavaScript 模块和 NgModule 之间的差异" target="_self">JS 模块 vs NgModule</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/frequent-ngmodules" title="介绍最常用的 NgModule" target="_self">常用模块</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/module-types" title="介绍特性模块的几种类型" target="_self">特性模块的分类</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/entry-components" title="关于 Angular 中入口组件的一切" target="_self">入口组件</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/feature-modules" title="创建特性模块，以组织你的代码" target="_self">特性模块</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/providers" title="服务提供商与 NgModule" target="_self">服务提供商</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/singleton-services" title="创建单例服务" target="_self">单例服务</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/lazy-loading-ngmodules" title="惰性加载模块，以提高应用的性能" target="_self">惰性加载的特性模块</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/sharing-ngmodules" title="共享 NgModule 让你的应用现代化。" target="_self">共享 NgModule</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/ngmodule-api" title="理解 NgModule 的那些细节。" target="_self">NgModule API</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/ngmodule-faq" title="回答关于 NgModules 的常见问题。" target="_self">NgModule 常见问题</a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-2 collapsed ng-star-inserted" type="button" title="依赖注入：创建并注入各种服务。" aria-pressed="false">依赖注入<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/dependency-injection" title="Angular 的依赖注入系统能够为 Angular 创建的类创建并交付它们所依赖的服务。" target="_self">Angular 依赖注入</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/hierarchical-dependency-injection" title="与组件树平行的注入器树，并支持嵌套的依赖。" target="_self">多级注入器</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/dependency-injection-providers" title="各种提供商类型的更多知识。" target="_self">DI 提供商</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/dependency-injection-in-action" title="依赖注入的使用技巧" target="_self">DI 实战</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/dependency-injection-navtree" title="使用注入器树来查找父组件。" target="_self">浏览组件树</a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 expanded selected ng-star-inserted" style="position:relative" href="guide/http" title="通过 HTTP 协议与远程服务器对话。" target="_self">HttpClient</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/router" title="揭示如何通过 Angular 路由进行基本的屏幕导航。" target="_self">路由与导航</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-2 collapsed ng-star-inserted" type="button" title="Angular 动画系统指南" aria-pressed="false">动画<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/animations" title="Angular 动画的基础技术。" target="_self">简介</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/transition-and-triggers" title="转场与触发器的高级技术。" target="_self">转场与触发器</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/complex-animation-sequences" title="复杂的 Angular 动画序列。" target="_self">复杂序列</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/reusable-animations" title="创建可复用的动画。" target="_self">可复用动画</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/route-animations" title="为路由提供转场动画。" target="_self">路由转场动画</a></div></aio-nav-item></div></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-1 collapsed ng-star-inserted" type="button" title="把 Angular 用到你的实际工作中的一些技巧" aria-pressed="false">其它技术<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/security" title="Angular 应用开发中的安全技术。" target="_self">安全</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/i18n" title="把应用模板中的文本翻译成多种语言。" target="_self">国际化 (i18n)</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-2 collapsed ng-star-inserted" type="button" title="Angular Service Worker: 控制应用资源的缓存。" aria-pressed="false">Service Worker 与 PWA<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/service-worker-intro" title="Angular 对 Service Worker 的实现提升了慢速或不稳定的网络连接下的用户体验。" target="_self">简介</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/service-worker-getting-started" title="在 CLI 项目中启用 Service Worker，并在浏览器中查看效果。" target="_self">快速起步</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/service-worker-communications" title="那些能让你和 Angular 的 Service Worker 通讯的服务类。" target="_self">与 Service Worker 通讯</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/service-worker-devops" title="使用 Service Worker 运行应用、管理应用更新、调试以及杀掉正在运行的应用。" target="_self">生产环境下的 Service Worker</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/service-worker-config" title="配置 Service Worker 的缓存行为。" target="_self">Service Worker 配置</a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/universal" title="使用 Angular Universal 在服务端渲染 HTML。" target="_self">服务端渲染</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-2 collapsed ng-star-inserted" type="button" title="把 AngularJS 应用增量式的升级到 Angular。" aria-pressed="false">从 AngularJS 升级<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/upgrade" title="把 AngularJS 应用增量式的升级到 Angular。" target="_self">升级步骤</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/upgrade-performance" title="用更灵活的方式把 AngularJS 升级到 Angular" target="_self">更关注性能的升级方式</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/ajs-quick-reference" title="学习如何把 AngularJS 的概念映射到 Angular 中。" target="_self">AngularJS 与 Angular 的概念对照</a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-2 collapsed ng-star-inserted" type="button" title="使用共享库扩展 Angular" aria-pressed="false">Angular 库开发<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/libraries" title="理解何时以及如何使用和创建库。" target="_self">库概览</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/using-libraries" title="把已发布的库集成进你的应用中。" target="_self">使用已发布的库</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/creating-libraries" title="通过创建、发布和使用你自己的库来扩展 Angular" target="_self">创建库</a></div></aio-nav-item></div></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-1 collapsed ng-star-inserted" type="button" title="关于环境搭建、构建、测试、部署环境与工具的信息。" aria-pressed="false">环境搭建与部署<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/file-structure" title="Angular 工作区在文件系统中是怎样的。" target="_self">项目文件结构</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/workspace-config" title="&quot;angular.json&quot; 包含供 CLI 命令使用的工作区和项目默认配置。" target="_self">工作区配置</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/npm-packages" title="开发期间和运行期间所需的 npm 包的说明。" target="_self">npm 包</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/typescript-configuration" title="给 Angular 开发者的 TypeScript 配置。" target="_self">TypeScript 配置</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/aot-compiler" title="了解为何以及如何使用预先（AOT）编译器。" target="_self">预先（AOT）编译</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/build" title="构建应用及为应用启动开发服务器。" target="_self">构建与运行</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/testing" title="测试 Angular 应用的技巧与实践。" target="_self">测试</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/deployment" title="了解如何部署 Angular 应用。" target="_self">发布</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/browser-support" title="浏览器支持与腻子脚本指南。" target="_self">浏览器支持</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-2 collapsed ng-star-inserted" type="button" title="整合开发环境和工具。" aria-pressed="false">开发工具集成<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-2 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-3 collapsed ng-star-inserted" style="position:relative" href="guide/language-service" title="使用 Angular 语言服务加速开发。" target="_self">语言服务</a></div></aio-nav-item></div></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-1 collapsed ng-star-inserted" type="button" title="Angular 的版本发布实践、更新与升级。" aria-pressed="false">发布信息<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/updating" title="如何把 Angular 应用和库升级到最新版本。" target="_self">保持最新</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/releases" title="Angular 的版本、发布、支持、弃用策略与实践。" target="_self">Angular 发布策略与实践</a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-1 collapsed ng-star-inserted" type="button" title="Angular 语法、编码、术语汇总。" aria-pressed="false">快捷手册<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/cheatsheet" title="关于 Angular 常用编码技术的快速指南。" target="_self">速查表</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/styleguide" title="写出 Angular 风格的程序" target="_self">风格指南</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="guide/glossary" title="Angular 中最重要的词汇的简要定义。" target="_self">词汇表</a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><button class="vertical-menu-item heading level-1 collapsed ng-star-inserted" type="button" title="Angular CLI 命令参考手册。" aria-pressed="false">CLI 命令<mat-icon class="rotating-icon mat-icon" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><div class="heading-children level-1 collapsed"><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli" title="CLI 工具介绍、命令、语法" target="_self">概览</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/add" title="ng add." target="_self">ng add</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/build" title="ng build." target="_self">ng build</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/config" title="ng config." target="_self">ng config</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/doc" title="ng doc." target="_self">ng doc</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/e2e" title="ng e2e." target="_self">ng e2e</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/generate" title="ng generate." target="_self">ng generate</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/help" title="ng help." target="_self">ng help</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/lint" title="ng lint." target="_self">ng lint</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/new" title="ng new." target="_self">ng new</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/run" title="ng run." target="_self">ng run</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/serve" title="ng serve." target="_self">ng serve</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/test" title="ng test." target="_self">ng test</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/update" title="ng update." target="_self">ng update</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/version" title="ng version." target="_self">ng version</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-2 collapsed ng-star-inserted" style="position:relative" href="cli/xi18n" title="ng xi18n." target="_self">ng xi18n</a></div></aio-nav-item></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="api" title="关于 Angular 中类和值的详细信息。" target="_self">API 参考手册</a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><div class="mat-divider ng-star-inserted" style="margin:4px 20px;border-top:1px solid #d3d3d3"></div></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="https://ng-china.org" title="2018 ngChina 开发者大会" target="_blank">2018 ngChina @ 杭州<mat-icon class="mat-icon material-icons ng-star-inserted" role="img" aria-hidden="true">open_in_new</mat-icon></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="https://github.com/ng-docs/ng-docs.github.io/issues" title="github 上的中文互助问答区" target="_blank">互助问答<mat-icon class="mat-icon material-icons ng-star-inserted" role="img" aria-hidden="true">open_in_new</mat-icon></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="https://material.angular.cn" title="Angular Material 组件库的中文文档" target="_blank">官方 Material 组件库<mat-icon class="mat-icon material-icons ng-star-inserted" role="img" aria-hidden="true">open_in_new</mat-icon></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="https://ng.ant.design/" title="Ant Design 的 Angular 实现，服务于企业级后台产品。" target="_blank">ng-zorro 组件库<mat-icon class="mat-icon material-icons ng-star-inserted" role="img" aria-hidden="true">open_in_new</mat-icon></a></div></aio-nav-item><aio-nav-item class="ng-star-inserted"><div class="ng-star-inserted"><a class="vertical-menu-item level-1 collapsed ng-star-inserted" style="position:relative" href="https://ng.mobile.ant.design/" title="Ant Design Mobile 的 Angular 实现，服务于无线产品。" target="_blank">ng-zorro mobile 组件库<mat-icon class="mat-icon material-icons ng-star-inserted" role="img" aria-hidden="true">open_in_new</mat-icon></a></div></aio-nav-item></aio-nav-menu><div class="doc-version"><aio-select><div class="form-select-menu"><button class="form-select-button"><strong></strong>stable (v8.0.0-beta.4)</button></div></aio-select></div></div></mat-sidenav><div class="cdk-visually-hidden cdk-focus-trap-anchor"></div><mat-sidenav-content cdkscrollable="" class="mat-drawer-content mat-sidenav-content ng-star-inserted" style="margin-left:260px"><main class="sidenav-content" role="main" id="guide-http"><aio-mode-banner></aio-mode-banner><aio-doc-viewer class=""><div style="opacity:1"><div class="github-links"><a href="https://github.com/angular/angular-cn/edit/aio/aio/content/guide/http.md?message=docs%3A%20请简述你的修改..." aria-label="提供编辑建议" title="提供编辑建议"><i class="material-icons" aria-hidden="true" role="img">mode_edit</i></a></div><div class="content"><h1 id="httpclient">HttpClient<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#httpclient"><i class="material-icons">link</i></a></h1><aio-toc class="embedded" ng-version="7.0.0"><div class="toc-inner no-print collapsed ng-star-inserted"><button aria-label="Expand/collapse contents" class="toc-heading embedded secondary ng-star-inserted" title="Expand/collapse contents" type="button" aria-pressed="false">目录<mat-icon class="rotating-icon mat-icon collapsed" role="img" svgicon="keyboard_arrow_right" aria-hidden="true"><svg focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"></path></svg></mat-icon></button><ul class="toc-list embedded"><li title="准备工作link" class="h2 ng-star-inserted"><a href="guide/http#setup">准备工作</a></li><li title="获取 JSON 数据link" class="h2 ng-star-inserted"><a href="guide/http#getting-json-data">获取 JSON 数据</a></li><li title="为什么要写服务link" class="h3 ng-star-inserted"><a href="guide/http#why-write-a-service">为什么要写服务</a></li><li title="带类型检查的响应link" class="h3 secondary ng-star-inserted"><a href="guide/http#type-checking-the-response">带类型检查的响应</a></li><li title="读取完整的响应体link" class="h3 secondary ng-star-inserted"><a href="guide/http#reading-the-full-response">读取完整的响应体</a></li><li title="错误处理link" class="h2 secondary ng-star-inserted"><a href="guide/http#error-handling">错误处理</a></li><li title="获取错误详情link" class="h3 secondary ng-star-inserted"><a href="guide/http#getting-error-details">获取错误详情</a></li><li title="retry()link" class="h3 secondary ng-star-inserted"><a href="guide/http#retry"><code>retry()</code></a></li><li title="可观察对象 (Observable) 与操作符 (operator)link" class="h2 secondary ng-star-inserted"><a href="guide/http#observables-and-operators">可观察对象 (Observable) 与操作符 (operator)</a></li><li title="请求非 JSON 格式的数据link" class="h2 secondary ng-star-inserted"><a href="guide/http#requesting-non-json-data">请求非 JSON 格式的数据</a></li><li title="把数据发送到服务器link" class="h2 secondary ng-star-inserted"><a href="guide/http#sending-data-to-the-server">把数据发送到服务器</a></li><li title="添加请求头link" class="h3 secondary ng-star-inserted"><a href="guide/http#adding-headers">添加请求头</a></li><li title="发起一个 POST 请求link" class="h3 secondary ng-star-inserted"><a href="guide/http#making-a-post-request">发起一个 POST 请求</a></li><li title="发起 DELETE 请求link" class="h3 secondary ng-star-inserted"><a href="guide/http#making-a-delete-request">发起 <code>DELETE</code> 请求</a></li><li title="发起 PUT 请求link" class="h3 secondary ng-star-inserted"><a href="guide/http#making-a-put-request">发起 PUT 请求</a></li><li title="高级用法link" class="h2 secondary ng-star-inserted"><a href="guide/http#advanced-usage">高级用法</a></li><li title="配置请求link" class="h3 secondary ng-star-inserted"><a href="guide/http#configuring-the-request">配置请求</a></li><li title="请求的防抖（debounce）link" class="h3 secondary ng-star-inserted"><a href="guide/http#debouncing-requests">请求的防抖（debounce）</a></li><li title="拦截请求和响应link" class="h3 secondary ng-star-inserted"><a href="guide/http#intercepting-requests-and-responses">拦截请求和响应</a></li><li title="监听进度事件link" class="h3 secondary ng-star-inserted"><a href="guide/http#listening-to-progress-events">监听进度事件</a></li><li title="安全：XSRF 防护link" class="h2 secondary ng-star-inserted"><a href="guide/http#security-xsrf-protection">安全：XSRF 防护</a></li><li title="配置自定义 cookie/header 名称link" class="h3 secondary ng-star-inserted"><a href="guide/http#configuring-custom-cookieheader-names">配置自定义 cookie/header 名称</a></li><li title="测试 HTTP 请求link" class="h2 secondary ng-star-inserted"><a href="guide/http#testing-http-requests">测试 HTTP 请求</a></li><li title="Mock 方法论link" class="h3 secondary ng-star-inserted"><a href="guide/http#mocking-philosophy">Mock 方法论</a></li><li title="搭建环境link" class="h3 secondary ng-star-inserted"><a href="guide/http#setup-1">搭建环境</a></li><li title="期待并回复请求link" class="h3 secondary ng-star-inserted"><a href="guide/http#expecting-and-answering-requests">期待并回复请求</a></li><li title="测试对错误的预期link" class="h3 secondary ng-star-inserted"><a href="guide/http#testing-for-errors">测试对错误的预期</a></li></ul><button aria-label="Expand/collapse contents" class="toc-more-items embedded material-icons collapsed ng-star-inserted" title="Expand/collapse contents" type="button" aria-pressed="false"></button></div></aio-toc><p translation-result="on">大多数前端应用都需要通过 HTTP 协议与后端服务器通讯。现代浏览器支持使用两种不同的 API 发起 HTTP 请求：<code>XMLHttpRequest</code> 接口和 <code>fetch()</code> API。</p><p translation-origin="off">Most front-end applications communicate with backend services over the HTTP protocol. Modern browsers support two different APIs for making HTTP requests: the <code>XMLHttpRequest</code> interface and the <code>fetch()</code> API.</p><p translation-result="on"><code>@angular/common/<a href="api/common/http" class="code-anchor">http</a></code> 中的 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 类为 Angular 应用程序提供了一个简化的 API 来实现 HTTP 客户端功能。它基于浏览器提供的 <code>XMLHttpRequest</code> 接口。 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 带来的其它优点包括：可测试性、强类型的请求和响应对象、发起请求与接收响应时的拦截器支持，以及更好的、基于可观察（Observable）对象的 API 以及流式错误处理机制。</p><p translation-origin="off">The <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> in <code>@angular/common/<a href="api/common/http" class="code-anchor">http</a></code> offers a simplified client HTTP API for Angular applications that rests on the <code>XMLHttpRequest</code> interface exposed by browsers. Additional benefits of <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> include testability features, typed request and response objects, request and response interception, <code>Observable</code> apis, and streamlined error handling.</p><p translation-result="on">你可以到<live-example ng-version="7.0.0"><span style="display:none"></span><span><span class="ng-star-inserted"><a target="_blank" href="generated/live-examples/http/stackblitz.html" title="在线例子">在线例子</a><span class="ng-star-inserted"> / <a download="" title="下载范例" href="generated/zips/http/http.zip">下载范例</a></span></span></span></live-example>中运行本章的代码。</p><p translation-origin="off">You can run the<live-example ng-version="7.0.0"><span style="display:none"></span><span><span class="ng-star-inserted"><a target="_blank" href="generated/live-examples/http/stackblitz.html" title="在线例子">在线例子</a><span class="ng-star-inserted"> / <a download="" title="下载范例" href="generated/zips/http/http.zip">下载范例</a></span></span></span></live-example>that accompanies this guide.</p><div class="alert is-helpful"><p translation-result="on">该应用代码并不需要数据服务器。 它基于 <a href="https://github.com/angular/in-memory-web-api/blob/master/README.md">Angular <em>in-memory-web-api</em></a> 库，该库会替换 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 模块中的 <code><a href="api/common/http/HttpBackend" class="code-anchor">HttpBackend</a></code>。用于替换的这个服务会模拟 REST 风格的后端的行为。</p><p translation-origin="off">The sample app does not require a data server. It relies on the <a href="https://github.com/angular/in-memory-web-api/blob/master/README.md">Angular <em>in-memory-web-api</em></a>, which replaces the <em>HttpClient</em> module's <code><a href="api/common/http/HttpBackend" class="code-anchor">HttpBackend</a></code>. The replacement service simulates the behavior of a REST-like backend.</p><p translation-result="on">到 <code>AppModule</code> 的 <code><a href="api/core/NgModule#imports" class="code-anchor">imports</a></code> 中查看这个库是如何配置的。</p><p translation-origin="off">Look at the <code>AppModule</code> <em>imports</em> to see how it is configured.</p></div><h2 id="setup" translation-result="on">准备工作<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#setup"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="setup">Setup<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#setup"><i class="material-icons">link</i></a></h2><p translation-result="on">要想使用 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code>，就要先导入 Angular 的 <code><a href="api/common/http/HttpClientModule" class="code-anchor">HttpClientModule</a></code>。大多数应用都会在根模块 <code>AppModule</code> 中导入它。</p><p translation-origin="off">Before you can use the <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code>, you need to import the Angular <code><a href="api/common/http/HttpClientModule" class="code-anchor">HttpClientModule</a></code>. Most apps do so in the root <code>AppModule</code>.</p><code-example path="http/src/app/app.module.ts" region="sketch" header="app/app.module.ts (excerpt)" linenums="false" ng-version="7.0.0"><div style="display:none">import { <a href="api/core/NgModule" class="code-anchor">NgModule</a> } from '@angular/core'; import { <a href="api/platform-browser/BrowserModule" class="code-anchor">BrowserModule</a> } from '@angular/platform-browser'; import { <a href="api/common/http/HttpClientModule" class="code-anchor">HttpClientModule</a> } from '@angular/common/<a href="api/common/http" class="code-anchor">http</a>'; @<a href="api/core/NgModule" class="code-anchor">NgModule</a>({ <a href="api/core/NgModule#imports" class="code-anchor">imports</a>: [ <a href="api/platform-browser/BrowserModule" class="code-anchor">BrowserModule</a>, // import <a href="api/common/http/HttpClientModule" class="code-anchor">HttpClientModule</a> after BrowserModule. <a href="api/common/http/HttpClientModule" class="code-anchor">HttpClientModule</a>, ], <a href="api/core/NgModule#declarations" class="code-anchor">declarations</a>: [ AppComponent, ], <a href="api/core/NgModule#bootstrap" class="code-anchor">bootstrap</a>: [ AppComponent ] }) export class AppModule {}</div><header class="ng-star-inserted">app/app.module.ts (excerpt)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/app.module.ts (excerpt)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/NgModule" class="code-anchor"><span class="typ">NgModule</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln">         </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core'</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/platform-browser/BrowserModule" class="code-anchor"><span class="typ">BrowserModule</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln">    </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/platform-browser'</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/common/http/HttpClientModule" class="code-anchor"><span class="typ">HttpClientModule</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/common/</span><a href="api/common/http" class="code-anchor"><span class="str">http</span></a><span class="str">'</span><span class="pun">;</span><span class="pln">

</span><span class="lit">@</span><a href="api/core/NgModule" class="code-anchor"><span class="lit">NgModule</span></a><span class="pun">({</span><span class="pln">
  </span><a href="api/core/NgModule#imports" class="code-anchor"><span class="pln">imports</span></a><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
    </span><a href="api/platform-browser/BrowserModule" class="code-anchor"><span class="typ">BrowserModule</span></a><span class="pun">,</span><span class="pln">
    </span><span class="com">// import </span><a href="api/common/http/HttpClientModule" class="code-anchor"><span class="com">HttpClientModule</span></a><span class="com"> after BrowserModule.</span><span class="pln">
    </span><a href="api/common/http/HttpClientModule" class="code-anchor"><span class="typ">HttpClientModule</span></a><span class="pun">,</span><span class="pln">
  </span><span class="pun">],</span><span class="pln">
  </span><a href="api/core/NgModule#declarations" class="code-anchor"><span class="pln">declarations</span></a><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
    </span><span class="typ">AppComponent</span><span class="pun">,</span><span class="pln">
  </span><span class="pun">],</span><span class="pln">
  </span><a href="api/core/NgModule#bootstrap" class="code-anchor"><span class="pln">bootstrap</span></a><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><span class="typ">AppComponent</span><span class="pln"> </span><span class="pun">]</span><span class="pln">
</span><span class="pun">})</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">AppModule</span><span class="pln"> </span><span class="pun">{}</span></code>
    </pre></aio-code></code-example><p translation-result="on">在 <code>AppModule</code> 中导入 <code><a href="api/common/http/HttpClientModule" class="code-anchor">HttpClientModule</a></code> 之后，你可以把 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 注入到应用类中，就像下面的 <code>ConfigService</code> 例子中这样。</p><p translation-origin="off">Having imported <code><a href="api/common/http/HttpClientModule" class="code-anchor">HttpClientModule</a></code> into the <code>AppModule</code>, you can inject the <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> into an application class as shown in the following <code>ConfigService</code> example.</p><code-example path="http/src/app/config/config.service.ts" region="proto" header="app/config/config.service.ts (excerpt)" linenums="false" ng-version="7.0.0"><div style="display:none">import { <a href="api/core/Injectable" class="code-anchor">Injectable</a> } from '@angular/core'; import { <a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a> } from '@angular/common/<a href="api/common/http" class="code-anchor">http</a>'; @<a href="api/core/Injectable" class="code-anchor">Injectable</a>() export class ConfigService { constructor(private <a href="api/common/http" class="code-anchor">http</a>: <a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a>) { } }</div><header class="ng-star-inserted">app/config/config.service.ts (excerpt)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/config/config.service.ts (excerpt)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/Injectable" class="code-anchor"><span class="typ">Injectable</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core'</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/common/http/HttpClient" class="code-anchor"><span class="typ">HttpClient</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/common/</span><a href="api/common/http" class="code-anchor"><span class="str">http</span></a><span class="str">'</span><span class="pun">;</span><span class="pln">

</span><span class="lit">@</span><a href="api/core/Injectable" class="code-anchor"><span class="lit">Injectable</span></a><span class="pun">()</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">ConfigService</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">constructor</span><span class="pun">(</span><span class="kwd">private</span><span class="pln"> </span><a href="api/common/http" class="code-anchor"><span class="pln">http</span></a><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpClient" class="code-anchor"><span class="typ">HttpClient</span></a><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><h2 id="getting-json-data" translation-result="on">获取 JSON 数据<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#getting-json-data"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="getting-json-data">Getting JSON data<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#getting-json-data"><i class="material-icons">link</i></a></h2><p translation-result="on">应用通常会从服务器上获取 JSON 数据。 比如，该应用可能要从服务器上获取配置文件 <code>config.json</code>，其中指定了一些特定资源的 URL。</p><p translation-origin="off">Applications often request JSON data from the server. For example, the app might need a configuration file on the server, <code>config.json</code>, that specifies resource URLs.</p><code-example path="http/src/assets/config.json" header="assets/config.json" linenums="false" ng-version="7.0.0"><div style="display:none">{ "heroesUrl": "api/heroes", "textfile": "assets/textfile.txt" }</div><header class="ng-star-inserted">assets/config.json</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from assets/config.json">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pun">{</span><span class="pln">
  </span><span class="str">"heroesUrl"</span><span class="pun">:</span><span class="pln"> </span><span class="str">"api/heroes"</span><span class="pun">,</span><span class="pln">
  </span><span class="str">"textfile"</span><span class="pun">:</span><span class="pln"> </span><span class="str">"assets/textfile.txt"</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>ConfigService</code> 会通过 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 的 <code>get()</code> 方法取得这个文件。</p><p translation-origin="off">The <code>ConfigService</code> fetches this file with a <code>get()</code> method on <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code>.</p><code-example path="http/src/app/config/config.service.ts" region="getConfig_1" header="app/config/config.service.ts (getConfig v.1)" linenums="false" ng-version="7.0.0"><div style="display:none">configUrl = 'assets/config.json'; getConfig() { return this.http.get(this.configUrl); }</div><header class="ng-star-inserted">app/config/config.service.ts (getConfig v.1)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/config/config.service.ts (getConfig v.1)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">configUrl </span><span class="pun">=</span><span class="pln"> </span><span class="str">'assets/config.json'</span><span class="pun">;</span><span class="pln">

getConfig</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">http</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">configUrl</span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">像 <code>ConfigComponent</code> 这样的组件会注入 <code>ConfigService</code>，并调用其 <code>getConfig</code> 方法。</p><p translation-origin="off">A component, such as <code>ConfigComponent</code>, injects the <code>ConfigService</code> and calls the <code>getConfig</code> service method.</p><code-example path="http/src/app/config/config.component.ts" region="v1" header="app/config/config.component.ts (showConfig v.1)" linenums="false" ng-version="7.0.0"><div style="display:none">showConfig() { this.configService.getConfig() .subscribe((data: Config) =&gt; this.config = { heroesUrl: data['heroesUrl'], textfile: data['textfile'] }); }</div><header class="ng-star-inserted">app/config/config.component.ts (showConfig v.1)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/config/config.component.ts (showConfig v.1)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">showConfig</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">configService</span><span class="pun">.</span><span class="pln">getConfig</span><span class="pun">()</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">((</span><span class="pln">data</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Config</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">config </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
        heroesUrl</span><span class="pun">:</span><span class="pln"> data</span><span class="pun">[</span><span class="str">'heroesUrl'</span><span class="pun">],</span><span class="pln">
        textfile</span><span class="pun">:</span><span class="pln">  data</span><span class="pun">[</span><span class="str">'textfile'</span><span class="pun">]</span><span class="pln">
    </span><span class="pun">});</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">这个服务方法返回配置数据的 <code>Observable</code> 对象，所以组件要<strong>订阅（subscribe）</strong> 该方法的返回值。 订阅时的回调函数会把这些数据字段复制到组件的 <code><a href="api/router/Router#config" class="code-anchor">config</a></code> 对象中，它会在组件的模板中绑定，以供显示。</p><p translation-origin="off">Because the service method returns an <code>Observable</code> of configuration data, the component <strong>subscribes</strong> to the method's return value. The subscription callback copies the data fields into the component's <code><a href="api/router/Router#config" class="code-anchor">config</a></code> object, which is data-bound in the component template for display.</p><h3 id="why-write-a-service" translation-result="on">为什么要写服务<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#why-write-a-service"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="why-write-a-service">Why write a service<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#why-write-a-service"><i class="material-icons">link</i></a></h3><p translation-result="on">这个例子太简单，所以它也可以在组件本身的代码中调用 <code><a href="api/http/Http#get" class="code-anchor">Http.get()</a></code>，而不用借助服务。</p><p translation-origin="off">This example is so simple that it is tempting to write the <code><a href="api/http/Http#get" class="code-anchor">Http.get()</a></code> inside the component itself and skip the service.</p><p translation-result="on">不过，数据访问很少能一直这么简单。 你通常要对数据做后处理、添加错误处理器，还可能加一些重试逻辑，以便应对网络抽风的情况。</p><p translation-origin="off">However, data access rarely stays this simple. You typically post-process the data, add error handling, and maybe some retry logic to cope with intermittent connectivity.</p><p translation-result="on">该组件很快就会因为这些数据方式的细节而变得杂乱不堪。 组件变得难以理解、难以测试，并且这些数据访问逻辑无法被复用，也无法标准化。</p><p translation-origin="off">The component quickly becomes cluttered with data access minutia. The component becomes harder to understand, harder to test, and the data access logic can't be re-used or standardized.</p><p translation-result="on">这就是为什么最佳实践中要求把数据展现逻辑从数据访问逻辑中拆分出去，也就是说把数据访问逻辑包装进一个单独的服务中， 并且在组件中把数据访问逻辑委托给这个服务。就算是这么简单的应用也要如此。</p><p translation-origin="off">That's why it is a best practice to separate presentation of data from data access by encapsulating data access in a separate service and delegating to that service in the component, even in simple cases like this one.</p><h3 id="type-checking-the-response" translation-result="on">带类型检查的响应<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#type-checking-the-response"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="type-checking-the-response">Type-checking the response<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#type-checking-the-response"><i class="material-icons">link</i></a></h3><p translation-result="on">该订阅的回调需要用通过括号中的语句来提取数据的值。</p><p translation-origin="off">The subscribe callback above requires bracket notation to extract the data values.</p><code-example path="http/src/app/config/config.component.ts" region="v1_callback" linenums="false" ng-version="7.0.0"><div style="display:none">.subscribe((data: Config) =&gt; this.config = { heroesUrl: data['heroesUrl'], textfile: data['textfile'] });</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">((</span><span class="pln">data</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Config</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">config </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    heroesUrl</span><span class="pun">:</span><span class="pln"> data</span><span class="pun">[</span><span class="str">'heroesUrl'</span><span class="pun">],</span><span class="pln">
    textfile</span><span class="pun">:</span><span class="pln">  data</span><span class="pun">[</span><span class="str">'textfile'</span><span class="pun">]</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">你没法写成 <code>data.heroesUrl</code> ，因为 TypeScript 会报告说来自服务器的 <code>data</code> 对象中没有名叫 <code>heroesUrl</code> 的属性。</p><p translation-origin="off">You can't write <code>data.heroesUrl</code> because TypeScript correctly complains that the <code>data</code> object from the service does not have a <code>heroesUrl</code> property.</p><p translation-result="on">这是因为 <code><a href="api/common/http/HttpClient#get" class="code-anchor">HttpClient.get()</a></code> 方法把 JSON 响应体解析成了匿名的 <code>Object</code> 类型。它不知道该对象的具体形态如何。</p><p translation-origin="off">The <code><a href="api/common/http/HttpClient#get" class="code-anchor">HttpClient.get()</a></code> method parsed the JSON server response into the anonymous <code>Object</code> type. It doesn't know what the shape of that object is.</p><p translation-result="on">你可以告诉 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 该响应体的类型，以便在消费这种输出时更容易、更明确。</p><p translation-origin="off">You can tell <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> the type of the response to make consuming the output easier and more obvious.</p><p translation-result="on">首先，定义一个具有正确形态的接口：</p><p translation-origin="off">First, define an interface with the correct shape:</p><code-example path="http/src/app/config/config.service.ts" region="config-interface" linenums="false" ng-version="7.0.0"><div style="display:none">export interface Config { heroesUrl: string; textfile: string; }</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">export</span><span class="pln"> </span><span class="kwd">interface</span><span class="pln"> </span><span class="typ">Config</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  heroesUrl</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">string</span><span class="pun">;</span><span class="pln">
  textfile</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">string</span><span class="pun">;</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">然后，在服务器中把该接口指定为 <code><a href="api/common/http/HttpClient#get" class="code-anchor">HttpClient.get()</a></code> 调用的类型参数。</p><p translation-origin="off">Then, specify that interface as the <code><a href="api/common/http/HttpClient#get" class="code-anchor">HttpClient.get()</a></code> call's type parameter in the service:</p><code-example path="http/src/app/config/config.service.ts" region="getConfig_2" header="app/config/config.service.ts (getConfig v.2)" linenums="false" ng-version="7.0.0"><div style="display:none">getConfig() { // now returns an Observable of Config return this.http.get&lt;Config&gt;(this.configUrl); }</div><header class="ng-star-inserted">app/config/config.service.ts (getConfig v.2)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/config/config.service.ts (getConfig v.2)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">getConfig</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// now returns an Observable of Config</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">http</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">&lt;</span><span class="typ">Config</span><span class="pun">&gt;(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">configUrl</span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">修改后的组件方法，其回调函数中获取一个带类型的对象，它易于使用，且消费起来更安全：</p><p translation-origin="off">The callback in the updated component method receives a typed data object, which is easier and safer to consume:</p><code-example path="http/src/app/config/config.component.ts" region="v2" header="app/config/config.component.ts (showConfig v.2)" linenums="false" ng-version="7.0.0"><div style="display:none"><a href="api/router/Router#config" class="code-anchor">config</a>: Config; showConfig() { this.configService.getConfig() // clone the data object, using its known Config shape .subscribe((data: Config) =&gt; this.config = { ...data }); }</div><header class="ng-star-inserted">app/config/config.component.ts (showConfig v.2)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/config/config.component.ts (showConfig v.2)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><a href="api/router/Router#config" class="code-anchor"><span class="pln">config</span></a><span class="pun">:</span><span class="pln"> </span><span class="typ">Config</span><span class="pun">;</span><span class="pln">

showConfig</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">configService</span><span class="pun">.</span><span class="pln">getConfig</span><span class="pun">()</span><span class="pln">
    </span><span class="com">// clone the data object, using its known Config shape</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">((</span><span class="pln">data</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Config</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">config </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="pun">...</span><span class="pln">data </span><span class="pun">});</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><h3 id="reading-the-full-response" translation-result="on">读取完整的响应体<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#reading-the-full-response"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="reading-the-full-response">Reading the full response<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#reading-the-full-response"><i class="material-icons">link</i></a></h3><p translation-result="on">响应体可能并不包含你需要的全部信息。有时候服务器会返回一个特殊的响应头或状态码，以标记出特定的条件，因此读取它们可能是必要的。</p><p translation-origin="off">The response body doesn't return all the data you may need. Sometimes servers return special headers or status codes to indicate certain conditions that are important to the application workflow.</p><p translation-result="on">要这样做，你就要通过 <code>observe</code> 选项来告诉 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code>，你想要完整的响应信息，而不是只有响应体：</p><p translation-origin="off">Tell <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> that you want the full response with the <code>observe</code> option:</p><code-example path="http/src/app/config/config.service.ts" region="getConfigResponse" linenums="false" ng-version="7.0.0"><div style="display:none">getConfigResponse(): Observable&lt;<a href="api/common/http/HttpResponse" class="code-anchor">HttpResponse</a>&lt;Config&gt;&gt; { return this.http.get&lt;Config&gt;( this.configUrl, { observe: 'response' }); }</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">getConfigResponse</span><span class="pun">():</span><span class="pln"> </span><span class="typ">Observable</span><span class="pun">&lt;</span><a href="api/common/http/HttpResponse" class="code-anchor"><span class="typ">HttpResponse</span></a><span class="pun">&lt;</span><span class="typ">Config</span><span class="pun">&gt;&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">http</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">&lt;</span><span class="typ">Config</span><span class="pun">&gt;(</span><span class="pln">
    </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">configUrl</span><span class="pun">,</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> observe</span><span class="pun">:</span><span class="pln"> </span><span class="str">'response'</span><span class="pln"> </span><span class="pun">});</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">现在 <code><a href="api/common/http/HttpClient#get" class="code-anchor">HttpClient.get()</a></code> 会返回一个 <code><a href="api/common/http/HttpResponse" class="code-anchor">HttpResponse</a></code> 类型的 <code>Observable</code>，而不只是 JSON 数据。</p><p translation-origin="off">Now <code><a href="api/common/http/HttpClient#get" class="code-anchor">HttpClient.get()</a></code> returns an <code>Observable</code> of typed <code><a href="api/common/http/HttpResponse" class="code-anchor">HttpResponse</a></code> rather than just the JSON data.</p><p translation-result="on">该组件的 <code>showConfigResponse()</code> 方法会像显示配置数据一样显示响应头：</p><p translation-origin="off">The component's <code>showConfigResponse()</code> method displays the response headers as well as the configuration:</p><code-example path="http/src/app/config/config.component.ts" region="showConfigResponse" header="app/config/config.component.ts (showConfigResponse)" linenums="false" ng-version="7.0.0"><div style="display:none">showConfigResponse() { this.configService.getConfigResponse() // resp is of type `<a href="api/common/http/HttpResponse" class="code-anchor">HttpResponse</a>&lt;Config&gt;` .subscribe(resp =&gt; { // display its headers const <a href="api/router/ParamMap#keys" class="code-anchor">keys</a> = resp.headers.keys(); this.headers = keys.map(key =&gt; `${key}: ${resp.headers.get(key)}`); // access the body directly, which is typed as `Config`. this.config = { ... resp.body }; }); }</div><header class="ng-star-inserted">app/config/config.component.ts (showConfigResponse)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/config/config.component.ts (showConfigResponse)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">showConfigResponse</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">configService</span><span class="pun">.</span><span class="pln">getConfigResponse</span><span class="pun">()</span><span class="pln">
    </span><span class="com">// resp is of type `</span><a href="api/common/http/HttpResponse" class="code-anchor"><span class="com">HttpResponse</span></a><span class="com">&lt;Config&gt;`</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">(</span><span class="pln">resp </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
      </span><span class="com">// display its headers</span><span class="pln">
      </span><span class="kwd">const</span><span class="pln"> </span><a href="api/router/ParamMap#keys" class="code-anchor"><span class="pln">keys</span></a><span class="pln"> </span><span class="pun">=</span><span class="pln"> resp</span><span class="pun">.</span><span class="pln">headers</span><span class="pun">.</span><span class="pln">keys</span><span class="pun">();</span><span class="pln">
      </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">headers </span><span class="pun">=</span><span class="pln"> keys</span><span class="pun">.</span><span class="pln">map</span><span class="pun">(</span><span class="pln">key </span><span class="pun">=&gt;</span><span class="pln">
        </span><span class="str">`${key}: ${resp.headers.get(key)}`</span><span class="pun">);</span><span class="pln">

      </span><span class="com">// access the body directly, which is typed as `Config`.</span><span class="pln">
      </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">config </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="pun">...</span><span class="pln"> resp</span><span class="pun">.</span><span class="pln">body </span><span class="pun">};</span><span class="pln">
    </span><span class="pun">});</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">如你所见，该响应对象具有一个带有正确类型的 <code>body</code> 属性。</p><p translation-origin="off">As you can see, the response object has a <code>body</code> property of the correct type.</p><h2 id="error-handling" translation-result="on">错误处理<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#error-handling"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="error-handling">Error handling<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#error-handling"><i class="material-icons">link</i></a></h2><p translation-result="on">如果这个请求导致了服务器错误怎么办？甚至，在烂网络下请求都没到服务器该怎么办？<code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 就会返回一个错误（error）而不再是成功的响应。</p><p translation-origin="off">What happens if the request fails on the server, or if a poor network connection prevents it from even reaching the server? <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> will return an <em>error</em> object instead of a successful response.</p><p translation-result="on">通过在 <code>.subscribe()</code> 中添加第二个回调函数，你<em>可以</em>在组件中处理它：</p><p translation-origin="off">You <em>could</em> handle in the component by adding a second callback to the <code>.subscribe()</code>:</p><code-example path="http/src/app/config/config.component.ts" region="v3" header="app/config/config.component.ts (showConfig v.3 with error handling)" linenums="false" ng-version="7.0.0"><div style="display:none">showConfig() { this.configService.getConfig() .subscribe( (data: Config) =&gt; this.config = { ...data }, // success path error =&gt; this.error = error // error path ); }</div><header class="ng-star-inserted">app/config/config.component.ts (showConfig v.3 with error handling)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/config/config.component.ts (showConfig v.3 with error handling)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">showConfig</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">configService</span><span class="pun">.</span><span class="pln">getConfig</span><span class="pun">()</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">(</span><span class="pln">
      </span><span class="pun">(</span><span class="pln">data</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Config</span><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">config </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="pun">...</span><span class="pln">data </span><span class="pun">},</span><span class="pln"> </span><span class="com">// success path</span><span class="pln">
      error </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">error </span><span class="pun">=</span><span class="pln"> error </span><span class="com">// error path</span><span class="pln">
    </span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">在数据访问失败时给用户一些反馈，确实是个好主意。 不过，直接显示由 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 返回的原始错误数据还远远不够。</p><p translation-origin="off">It's certainly a good idea to give the user some kind of feedback when data access fails. But displaying the raw error object returned by <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> is far from the best way to do it.</p><a id="error-details"></a><h3 id="getting-error-details" translation-result="on">获取错误详情<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#getting-error-details"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="getting-error-details">Getting error details<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#getting-error-details"><i class="material-icons">link</i></a></h3><p translation-result="on">检测错误的发生是第一步，不过如果知道具体发生了什么错误才会更有用。上面例子中传给回调函数的 <code>err</code> 参数的类型是 <code><a href="api/common/http/HttpErrorResponse" class="code-anchor">HttpErrorResponse</a></code>，它包含了这个错误中一些很有用的信息。</p><p translation-origin="off">Detecting that an error occurred is one thing. Interpreting that error and composing a user-friendly response is a bit more involved.</p><p translation-result="on">可能发生的错误分为两种。如果后端返回了一个失败的返回码（如 404、500 等），它会返回一个错误响应体。</p><p translation-origin="off">Two types of errors can occur. The server backend might reject the request, returning an HTTP response with a status code such as 404 or 500. These are error <em>responses</em>.</p><p translation-result="on">或者，如果在客户端这边出了错误（比如在 RxJS 操作符 (operator) 中抛出的异常或某些阻碍完成这个请求的网络错误），就会抛出一个 <code>Error</code> 类型的异常。</p><p translation-origin="off">Or something could go wrong on the client-side such as a network error that prevents the request from completing successfully or an exception thrown in an RxJS operator. These errors produce JavaScript <code>ErrorEvent</code> objects.</p><p translation-result="on"><code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 会在 <code><a href="api/common/http/HttpErrorResponse" class="code-anchor">HttpErrorResponse</a></code> 中捕获所有类型的错误信息，你可以查看这个响应体以了解到底发生了什么。</p><p translation-origin="off">The <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> captures both kinds of errors in its <code><a href="api/common/http/HttpErrorResponse" class="code-anchor">HttpErrorResponse</a></code> and you can inspect that response to figure out what really happened.</p><p translation-result="on">错误的探查、解释和解决是你应该在<em>服务</em>中做的事情，而不是在<em>组件</em>中。</p><p translation-origin="off">Error inspection, interpretation, and resolution is something you want to do in the <em>service</em>, not in the <em>component</em>.</p><p translation-result="on">你可能首先要设计一个错误处理器，就像这样：</p><p translation-origin="off">You might first devise an error handler like this one:</p><code-example path="http/src/app/config/config.service.ts" region="handleError" header="app/config/config.service.ts (handleError)" linenums="false" ng-version="7.0.0"><div style="display:none">private handleError(error: <a href="api/common/http/HttpErrorResponse" class="code-anchor">HttpErrorResponse</a>) { if (error.error instanceof ErrorEvent) { // A client-side or network error occurred. Handle it accordingly. console.error('An error occurred:', error.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, console.error( `Backend returned code ${error.status}, ` + `body was: ${error.error}`); } // return an observable with <a href="api/router/RouterLinkWithHref" class="code-anchor">a</a> user-facing error <a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a> return throwError( 'Something bad happened; please try again later.'); };</div><header class="ng-star-inserted">app/config/config.service.ts (handleError)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/config/config.service.ts (handleError)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">private</span><span class="pln"> handleError</span><span class="pun">(</span><span class="pln">error</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpErrorResponse" class="code-anchor"><span class="typ">HttpErrorResponse</span></a><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="pln">error</span><span class="pun">.</span><span class="pln">error </span><span class="kwd">instanceof</span><span class="pln"> </span><span class="typ">ErrorEvent</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="com">// A client-side or network error occurred. Handle it accordingly.</span><span class="pln">
    console</span><span class="pun">.</span><span class="pln">error</span><span class="pun">(</span><span class="str">'An error occurred:'</span><span class="pun">,</span><span class="pln"> error</span><span class="pun">.</span><span class="pln">error</span><span class="pun">.</span><span class="pln">message</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">else</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="com">// The backend returned an unsuccessful response code.</span><span class="pln">
    </span><span class="com">// The response body may contain clues as to what went wrong,</span><span class="pln">
    console</span><span class="pun">.</span><span class="pln">error</span><span class="pun">(</span><span class="pln">
      </span><span class="str">`Backend returned code ${error.status}, `</span><span class="pln"> </span><span class="pun">+</span><span class="pln">
      </span><span class="str">`body was: ${error.error}`</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
  </span><span class="com">// return an observable with </span><a href="api/router/RouterLinkWithHref" class="code-anchor"><span class="com">a</span></a><span class="com"> user-facing error </span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="com">message</span></a><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> throwError</span><span class="pun">(</span><span class="pln">
    </span><span class="str">'Something bad happened; please try again later.'</span><span class="pun">);</span><span class="pln">
</span><span class="pun">};</span></code>
    </pre></aio-code></code-example><p translation-result="on">注意，该处理器返回一个带有用户友好的错误信息的 RxJS <a href="guide/http#rxjs"><code>ErrorObservable</code></a>对象。 该服务的消费者期望服务的方法返回某种形式的 <code>Observable</code>，就算是“错误的”也可以。</p><p translation-origin="off">Notice that this handler returns an RxJS <a href="guide/http#rxjs"><code>ErrorObservable</code></a>with a user-friendly error message. Consumers of the service expect service methods to return an <code>Observable</code> of some kind, even a "bad" one.</p><p translation-result="on">现在，你获取了由 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 方法返回的 <code>Observable</code>，并<em>把它们通过管道</em>传给错误处理器。</p><p translation-origin="off">Now you take the <code>Observables</code> returned by the <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> methods and <em>pipe them through</em> to the error handler.</p><code-example path="http/src/app/config/config.service.ts" region="getConfig_3" header="app/config/config.service.ts (getConfig v.3 with error handler)" linenums="false" ng-version="7.0.0"><div style="display:none">getConfig() { return this.http.get&lt;Config&gt;(this.configUrl) .pipe( catchError(this.handleError) ); }</div><header class="ng-star-inserted">app/config/config.service.ts (getConfig v.3 with error handler)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/config/config.service.ts (getConfig v.3 with error handler)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">getConfig</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">http</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">&lt;</span><span class="typ">Config</span><span class="pun">&gt;(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">configUrl</span><span class="pun">)</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">pipe</span><span class="pun">(</span><span class="pln">
      catchError</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">handleError</span><span class="pun">)</span><span class="pln">
    </span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><h3 id="retry"><code>retry()</code><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#retry"><i class="material-icons">link</i></a></h3><p translation-result="on">有时候，错误只是临时性的，只要重试就可能会自动消失。 比如，在移动端场景中可能会遇到网络中断的情况，只要重试一下就能拿到正确的结果。</p><p translation-origin="off">Sometimes the error is transient and will go away automatically if you try again. For example, network interruptions are common in mobile scenarios, and trying again may produce a successful result.</p><p translation-result="on"><a href="guide/http#rxjs">RxJS 库</a>提供了几个 <code>retry</code> 操作符，它们值得仔细看看。 其中最简单的是 <code>retry()</code>，它可以对失败的 <code>Observable</code> 自动重新订阅几次。对 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 方法调用的结果进行<em>重新订阅</em>会导致重新发起 HTTP 请求。</p><p translation-origin="off">The <a href="guide/http#rxjs">RxJS library</a> offers several <em>retry</em> operators that are worth exploring. The simplest is called <code>retry()</code> and it automatically re-subscribes to a failed <code>Observable</code> a specified number of times. <em>Re-subscribing</em> to the result of an <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> method call has the effect of reissuing the HTTP request.</p><p translation-result="on">把它插入到 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 方法结果的<em>管道</em>中，就放在错误处理器的紧前面。</p><p translation-origin="off"><em>Pipe</em> it onto the <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> method result just before the error handler.</p><code-example path="http/src/app/config/config.service.ts" region="getConfig" header="app/config/config.service.ts (getConfig with retry)" linenums="false" ng-version="7.0.0"><div style="display:none">getConfig() { return this.http.get&lt;Config&gt;(this.configUrl) .pipe( retry(3), // retry <a href="api/router/RouterLinkWithHref" class="code-anchor">a</a> failed request up to 3 times catchError(this.handleError) // then handle the error ); }</div><header class="ng-star-inserted">app/config/config.service.ts (getConfig with retry)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/config/config.service.ts (getConfig with retry)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">getConfig</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">http</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">&lt;</span><span class="typ">Config</span><span class="pun">&gt;(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">configUrl</span><span class="pun">)</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">pipe</span><span class="pun">(</span><span class="pln">
      </span><span class="kwd">retry</span><span class="pun">(</span><span class="lit">3</span><span class="pun">),</span><span class="pln"> </span><span class="com">// retry </span><a href="api/router/RouterLinkWithHref" class="code-anchor"><span class="com">a</span></a><span class="com"> failed request up to 3 times</span><span class="pln">
      catchError</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">handleError</span><span class="pun">)</span><span class="pln"> </span><span class="com">// then handle the error</span><span class="pln">
    </span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><a id="rxjs"></a><h2 id="observables-and-operators" translation-result="on">可观察对象 (Observable) 与操作符 (operator)<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#observables-and-operators"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="observables-and-operators">Observables and operators<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#observables-and-operators"><i class="material-icons">link</i></a></h2><p translation-result="on">本章的前一节中引用了 RxJS 的 <code>Observable</code> 和 <code>operator</code>，比如 <code>catchError</code> 和 <code>retry</code>。 接下来你还会遇到更多 RxJS 中的概念。</p><p translation-origin="off">The previous sections of this guide referred to RxJS <code>Observables</code> and operators such as <code>catchError</code> and <code>retry</code>. You will encounter more RxJS artifacts as you continue below.</p><p translation-result="on"><a href="http://reactivex.io/rxjs/">RxJS</a> 是一个库，用于把异步调用和基于回调的代码组合成<em>函数式（functional）的</em>、<em>响应式（reactive）的</em>风格。 很多 Angular API，包括 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 都会生成和消费 RxJS 的 <code>Observable</code>。</p><p translation-origin="off"><a href="http://reactivex.io/rxjs/">RxJS</a> is a library for composing asynchronous and callback-based code in a <em>functional, reactive style</em>. Many Angular APIs, including <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code>, produce and consume RxJS <code>Observables</code>.</p><p translation-result="on">RxJS 本身超出了本章的范围。你可以在网络上找到更多的学习资源。 虽然只用少量的 RxJS 知识就可以获得解决方案，不过以后你会逐步提高 RxJS 技能，以便更高效的使用 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code>。</p><p translation-origin="off">RxJS itself is out-of-scope for this guide. You will find many learning resources on the web. While you can get by with a minimum of RxJS knowledge, you'll want to grow your RxJS skills over time in order to use <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> effectively.</p><p translation-result="on">如果你在跟着教程敲下面这些代码片段，要注意你要自己导入这里出现的 RxJS 的可观察对象和操作符。就像 <code>ConfigService</code> 中的这些导入。</p><p translation-origin="off">If you're following along with these code snippets, note that you must import the RxJS observable and operator symbols that appear in those snippets. These <code>ConfigService</code> imports are typical.</p><code-example path="http/src/app/config/config.service.ts" region="rxjs-imports" header="app/config/config.service.ts (RxJS imports)" linenums="false" ng-version="7.0.0"><div style="display:none">import { Observable, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators';</div><header class="ng-star-inserted">app/config/config.service.ts (RxJS imports)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/config/config.service.ts (RxJS imports)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">Observable</span><span class="pun">,</span><span class="pln"> throwError </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'rxjs'</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> catchError</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">retry</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'rxjs/operators'</span><span class="pun">;</span></code>
    </pre></aio-code></code-example><h2 id="requesting-non-json-data" translation-result="on">请求非 JSON 格式的数据<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#requesting-non-json-data"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="requesting-non-json-data">Requesting non-JSON data<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#requesting-non-json-data"><i class="material-icons">link</i></a></h2><p translation-result="on">不是所有的 API 都会返回 JSON 数据。在下面这个例子中，<code>DownloaderService</code> 中的方法会从服务器读取文本文件， 并把文件的内容记录下来，然后把这些内容使用 <code>Observable&lt;string&gt;</code> 的形式返回给调用者。</p><p translation-origin="off">Not all APIs return JSON data. In this next example, a <code>DownloaderService</code> method reads a text file from the server and logs the file contents, before returning those contents to the caller as an <code>Observable&lt;string&gt;</code>.</p><code-example path="http/src/app/downloader/downloader.service.ts" region="getTextFile" header="app/downloader/downloader.service.ts (getTextFile)" linenums="false" ng-version="7.0.0"><div style="display:none">getTextFile(filename: string) { // The Observable returned by get() is of type Observable&lt;string&gt; // because <a href="api/router/RouterLinkWithHref" class="code-anchor">a</a> text response was specified. // There's no need to pass <a href="api/router/RouterLinkWithHref" class="code-anchor">a</a> &lt;string&gt; type parameter to get(). return this.http.get(filename, {responseType: 'text'}) .pipe( tap( // Log the result or error data =&gt; this.log(filename, data), error =&gt; this.logError(filename, error) ) ); }</div><header class="ng-star-inserted">app/downloader/downloader.service.ts (getTextFile)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/downloader/downloader.service.ts (getTextFile)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">getTextFile</span><span class="pun">(</span><span class="pln">filename</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">string</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// The Observable returned by get() is of type Observable&lt;string&gt;</span><span class="pln">
  </span><span class="com">// because </span><a href="api/router/RouterLinkWithHref" class="code-anchor"><span class="com">a</span></a><span class="com"> text response was specified.</span><span class="pln">
  </span><span class="com">// There's no need to pass </span><a href="api/router/RouterLinkWithHref" class="code-anchor"><span class="com">a</span></a><span class="com"> &lt;string&gt; type parameter to get().</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">http</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">(</span><span class="pln">filename</span><span class="pun">,</span><span class="pln"> </span><span class="pun">{</span><span class="pln">responseType</span><span class="pun">:</span><span class="pln"> </span><span class="str">'text'</span><span class="pun">})</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">pipe</span><span class="pun">(</span><span class="pln">
      tap</span><span class="pun">(</span><span class="pln"> </span><span class="com">// Log the result or error</span><span class="pln">
        data </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">log</span><span class="pun">(</span><span class="pln">filename</span><span class="pun">,</span><span class="pln"> data</span><span class="pun">),</span><span class="pln">
        error </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">logError</span><span class="pun">(</span><span class="pln">filename</span><span class="pun">,</span><span class="pln"> error</span><span class="pun">)</span><span class="pln">
      </span><span class="pun">)</span><span class="pln">
    </span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">这里的 <code><a href="api/common/http/HttpClient#get" class="code-anchor">HttpClient.get()</a></code> 返回字符串而不是默认的 JSON 对象，因为它的 <code>responseType</code> 选项是 <code>'text'</code>。</p><p translation-origin="off"><code><a href="api/common/http/HttpClient#get" class="code-anchor">HttpClient.get()</a></code> returns a string rather than the default JSON because of the <code>responseType</code> option.</p><p translation-result="on">RxJS 的 <code>tap</code> 操作符（可看做 wiretap - 窃听），让这段代码探查由可观察对象传过来的正确值和错误值，而不用打扰它们。</p><p translation-origin="off">The RxJS <code>tap</code> operator (as in "wiretap") lets the code inspect good and error values passing through the observable without disturbing them.</p><p translation-result="on">在 <code>DownloaderComponent</code> 中的 <code>download()</code> 方法通过订阅这个服务中的方法来发起一次请求。</p><p translation-origin="off">A <code>download()</code> method in the <code>DownloaderComponent</code> initiates the request by subscribing to the service method.</p><code-example path="http/src/app/downloader/downloader.component.ts" region="download" header="app/downloader/downloader.component.ts (download)" linenums="false" ng-version="7.0.0"><div style="display:none">download() { this.downloaderService.getTextFile('assets/textfile.txt') .subscribe(results =&gt; this.contents = results); }</div><header class="ng-star-inserted">app/downloader/downloader.component.ts (download)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/downloader/downloader.component.ts (download)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">download</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">downloaderService</span><span class="pun">.</span><span class="pln">getTextFile</span><span class="pun">(</span><span class="str">'assets/textfile.txt'</span><span class="pun">)</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">(</span><span class="pln">results </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">contents </span><span class="pun">=</span><span class="pln"> results</span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><h2 id="sending-data-to-the-server" translation-result="on">把数据发送到服务器<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#sending-data-to-the-server"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="sending-data-to-the-server">Sending data to the server<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#sending-data-to-the-server"><i class="material-icons">link</i></a></h2><p translation-result="on">除了从服务器获取数据之外，<code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 还支持修改型的请求，也就是说，通过 <code>PUT</code>、<code>POST</code>、<code>DELETE</code> 这样的 HTTP 方法把数据发送到服务器。</p><p translation-origin="off">In addition to fetching data from the server, <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> supports mutating requests, that is, sending data to the server with other HTTP methods such as PUT, POST, and DELETE.</p><p translation-result="on">本指南中的这个范例应用包括一个简化版本的《英雄指南》，它会获取英雄数据，并允许用户添加、删除和修改它们。</p><p translation-origin="off">The sample app for this guide includes a simplified version of the "Tour of Heroes" example that fetches heroes and enables users to add, delete, and update them.</p><p translation-result="on">下面的这些章节中包括该范例的 <code>HeroesService</code> 中的一些方法片段。</p><p translation-origin="off">The following sections excerpt methods of the sample's <code>HeroesService</code>.</p><h3 id="adding-headers" translation-result="on">添加请求头<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#adding-headers"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="adding-headers">Adding headers<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#adding-headers"><i class="material-icons">link</i></a></h3><p translation-result="on">很多服务器在进行保存型操作时需要额外的请求头。 比如，它们可能需要一个 <code>Content-Type</code> 头来显式定义请求体的 MIME 类型。 也可能服务器会需要一个认证用的令牌（token）。</p><p translation-origin="off">Many servers require extra headers for save operations. For example, they may require a "Content-Type" header to explicitly declare the MIME type of the request body. Or perhaps the server requires an authorization token.</p><p translation-result="on"><code>HeroesService</code> 在 <code>httpOptions</code> 对象中就定义了一些这样的请求头，并把它传给每个 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 的保存型方法。</p><p translation-origin="off">The <code>HeroesService</code> defines such headers in an <code>httpOptions</code> object that will be passed to every <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> save method.</p><code-example path="http/src/app/heroes/heroes.service.ts" region="http-options" header="app/heroes/heroes.service.ts (httpOptions)" linenums="false" ng-version="7.0.0"><div style="display:none">import { <a href="api/common/http/HttpHeaders" class="code-anchor">HttpHeaders</a> } from '@angular/common/<a href="api/common/http" class="code-anchor">http</a>'; const httpOptions = { headers: new <a href="api/common/http/HttpHeaders" class="code-anchor">HttpHeaders</a>({ 'Content-Type': 'application/json', 'Authorization': 'my-auth-token' }) };</div><header class="ng-star-inserted">app/heroes/heroes.service.ts (httpOptions)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/heroes/heroes.service.ts (httpOptions)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/common/http/HttpHeaders" class="code-anchor"><span class="typ">HttpHeaders</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/common/</span><a href="api/common/http" class="code-anchor"><span class="str">http</span></a><span class="str">'</span><span class="pun">;</span><span class="pln">

</span><span class="kwd">const</span><span class="pln"> httpOptions </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  headers</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><a href="api/common/http/HttpHeaders" class="code-anchor"><span class="typ">HttpHeaders</span></a><span class="pun">({</span><span class="pln">
    </span><span class="str">'Content-Type'</span><span class="pun">:</span><span class="pln">  </span><span class="str">'application/json'</span><span class="pun">,</span><span class="pln">
    </span><span class="str">'Authorization'</span><span class="pun">:</span><span class="pln"> </span><span class="str">'my-auth-token'</span><span class="pln">
  </span><span class="pun">})</span><span class="pln">
</span><span class="pun">};</span></code>
    </pre></aio-code></code-example><h3 id="making-a-post-request" translation-result="on">发起一个 POST 请求<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#making-a-post-request"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="making-a-post-request">Making a POST request<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#making-a-post-request"><i class="material-icons">link</i></a></h3><p translation-result="on">应用经常把数据 <code>POST</code> 到服务器。它们会在提交表单时进行 <code>POST</code>。 下面这个例子中，<code>HeroesService</code> 在把英雄添加到数据库中时，就会使用 <code>POST</code>。</p><p translation-origin="off">Apps often POST data to a server. They POST when submitting a form. In the following example, the <code>HeroesService</code> posts when adding a hero to the database.</p><code-example path="http/src/app/heroes/heroes.service.ts" region="addHero" header="app/heroes/heroes.service.ts (addHero)" linenums="false" ng-version="7.0.0"><div style="display:none">/** POST: add <a href="api/router/RouterLinkWithHref" class="code-anchor">a</a> new hero to the database */ addHero (hero: Hero): Observable&lt;Hero&gt; { return this.http.post&lt;Hero&gt;(this.heroesUrl, hero, httpOptions) .pipe( catchError(this.handleError('addHero', hero)) ); }</div><header class="ng-star-inserted">app/heroes/heroes.service.ts (addHero)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/heroes/heroes.service.ts (addHero)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">/** POST: add </span><a href="api/router/RouterLinkWithHref" class="code-anchor"><span class="com">a</span></a><span class="com"> new hero to the database */</span><span class="pln">
addHero </span><span class="pun">(</span><span class="pln">hero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">):</span><span class="pln"> </span><span class="typ">Observable</span><span class="pun">&lt;</span><span class="typ">Hero</span><span class="pun">&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">http</span><span class="pun">.</span><span class="pln">post</span><span class="pun">&lt;</span><span class="typ">Hero</span><span class="pun">&gt;(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">heroesUrl</span><span class="pun">,</span><span class="pln"> hero</span><span class="pun">,</span><span class="pln"> httpOptions</span><span class="pun">)</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">pipe</span><span class="pun">(</span><span class="pln">
      catchError</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">handleError</span><span class="pun">(</span><span class="str">'addHero'</span><span class="pun">,</span><span class="pln"> hero</span><span class="pun">))</span><span class="pln">
    </span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code><a href="api/common/http/HttpClient#post" class="code-anchor">HttpClient.post()</a></code> 方法像 <code>get()</code> 一样也有类型参数（你会希望服务器返回一个新的英雄对象），它包含一个资源 URL。</p><p translation-origin="off">The <code><a href="api/common/http/HttpClient#post" class="code-anchor">HttpClient.post()</a></code> method is similar to <code>get()</code> in that it has a type parameter (you're expecting the server to return the new hero) and it takes a resource URL.</p><p translation-result="on">它还接受另外两个参数：</p><p translation-origin="off">It takes two more parameters:</p><ol><li><p translation-result="on"><code>hero</code> - 要 <code>POST</code> 的请求体数据。</p><p translation-origin="off"><code>hero</code> - the data to POST in the body of the request.</p></li><li><p translation-result="on"><code>httpOptions</code> - 这个例子中，该方法的选项<a href="guide/http#adding-headers">指定了所需的请求头</a>。</p><p translation-origin="off"><code>httpOptions</code> - the method options which, in this case, <a href="guide/http#adding-headers">specify required headers</a>.</p></li></ol><p translation-result="on">当然，它捕获错误的方式很像<a href="guide/http#error-details">前面描述的</a>操作方式。</p><p translation-origin="off">Of course it catches errors in much the same manner <a href="guide/http#error-details">described above</a>.</p><p translation-result="on"><code>HeroesComponent</code> 通过订阅该服务方法返回的 <code>Observable</code> 发起了一次实际的 <code>POST</code> 操作。</p><p translation-origin="off">The <code>HeroesComponent</code> initiates the actual POST operation by subscribing to the <code>Observable</code> returned by this service method.</p><code-example path="http/src/app/heroes/heroes.component.ts" region="add-hero-subscribe" header="app/heroes/heroes.component.ts (addHero)" linenums="false" ng-version="7.0.0"><div style="display:none">this.heroesService.addHero(newHero) .subscribe(hero =&gt; this.heroes.push(hero));</div><header class="ng-star-inserted">app/heroes/heroes.component.ts (addHero)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/heroes/heroes.component.ts (addHero)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">this</span><span class="pun">.</span><span class="pln">heroesService</span><span class="pun">.</span><span class="pln">addHero</span><span class="pun">(</span><span class="pln">newHero</span><span class="pun">)</span><span class="pln">
  </span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">(</span><span class="pln">hero </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">heroes</span><span class="pun">.</span><span class="pln">push</span><span class="pun">(</span><span class="pln">hero</span><span class="pun">));</span></code>
    </pre></aio-code></code-example><p translation-result="on">当服务器成功做出响应时，会带有这个新创建的英雄，然后该组件就会把这个英雄添加到正在显示的 <code>heroes</code> 列表中。</p><p translation-origin="off">When the server responds successfully with the newly added hero, the component adds that hero to the displayed <code>heroes</code> list.</p><h3 id="making-a-delete-request" translation-result="on">发起 <code>DELETE</code> 请求<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#making-a-delete-request"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="making-a-delete-request">Making a DELETE request<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#making-a-delete-request"><i class="material-icons">link</i></a></h3><p translation-result="on">该应用可以把英雄的 id 传给 <code>HttpClient.delete</code> 方法的请求 URL 来删除一个英雄。</p><p translation-origin="off">This application deletes a hero with the <code>HttpClient.delete</code> method by passing the hero's id in the request URL.</p><code-example path="http/src/app/heroes/heroes.service.ts" region="deleteHero" header="app/heroes/heroes.service.ts (deleteHero)" linenums="false" ng-version="7.0.0"><div style="display:none">/** DELETE: delete the hero from the server */ deleteHero (id: number): Observable&lt;{}&gt; { const url = `${this.heroesUrl}/${id}`; // DELETE api/heroes/42 return this.http.delete(url, httpOptions) .pipe( catchError(this.handleError('deleteHero')) ); }</div><header class="ng-star-inserted">app/heroes/heroes.service.ts (deleteHero)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/heroes/heroes.service.ts (deleteHero)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">/** DELETE: delete the hero from the server */</span><span class="pln">
deleteHero </span><span class="pun">(</span><span class="pln">id</span><span class="pun">:</span><span class="pln"> number</span><span class="pun">):</span><span class="pln"> </span><span class="typ">Observable</span><span class="pun">&lt;{}&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> url </span><span class="pun">=</span><span class="pln"> </span><span class="str">`${this.heroesUrl}/${id}`</span><span class="pun">;</span><span class="pln"> </span><span class="com">// DELETE api/heroes/42</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">http</span><span class="pun">.</span><span class="kwd">delete</span><span class="pun">(</span><span class="pln">url</span><span class="pun">,</span><span class="pln"> httpOptions</span><span class="pun">)</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">pipe</span><span class="pun">(</span><span class="pln">
      catchError</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">handleError</span><span class="pun">(</span><span class="str">'deleteHero'</span><span class="pun">))</span><span class="pln">
    </span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">当 <code>HeroesComponent</code> 订阅了该服务方法返回的 <code>Observable</code> 时，就会发起一次实际的 <code>DELETE</code> 操作。</p><p translation-origin="off">The <code>HeroesComponent</code> initiates the actual DELETE operation by subscribing to the <code>Observable</code> returned by this service method.</p><code-example path="http/src/app/heroes/heroes.component.ts" region="delete-hero-subscribe" header="app/heroes/heroes.component.ts (deleteHero)" linenums="false" ng-version="7.0.0"><div style="display:none">this.heroesService.deleteHero(hero.id).subscribe();</div><header class="ng-star-inserted">app/heroes/heroes.component.ts (deleteHero)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/heroes/heroes.component.ts (deleteHero)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">this</span><span class="pun">.</span><span class="pln">heroesService</span><span class="pun">.</span><span class="pln">deleteHero</span><span class="pun">(</span><span class="pln">hero</span><span class="pun">.</span><span class="pln">id</span><span class="pun">).</span><span class="pln">subscribe</span><span class="pun">();</span></code>
    </pre></aio-code></code-example><p translation-result="on">该组件不会等待删除操作的结果，所以它的 subscribe （订阅）中没有回调函数。不过就算你不关心结果，也仍然要订阅它。调用 <code>subscribe()</code> 方法会<strong>执行</strong>这个可观察对象，这时才会真的发起 DELETE 请求。</p><p translation-origin="off">The component isn't expecting a result from the delete operation, so it subscribes without a callback. Even though you are not using the result, you still have to subscribe. Calling the <code>subscribe()</code> method <em>executes</em> the observable, which is what initiates the DELETE request.</p><div class="alert is-important"><p translation-result="on">你必须调用 <code>subscribe()</code>，否则什么都不会发生。仅仅调用 <code>HeroesService.deleteHero()</code> 是<strong>不会发起 DELETE 请求的。</strong></p><p translation-origin="off">You must call <em>subscribe()</em> or nothing happens. Just calling <code>HeroesService.deleteHero()</code> <strong>does not initiate the DELETE request.</strong></p></div><code-example path="http/src/app/heroes/heroes.component.ts" region="delete-hero-no-subscribe" linenums="false" ng-version="7.0.0"><div style="display:none">// oops ... subscribe() is missing so nothing happens this.heroesService.deleteHero(hero.id);</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// oops ... subscribe() is missing so nothing happens</span><span class="pln">
</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">heroesService</span><span class="pun">.</span><span class="pln">deleteHero</span><span class="pun">(</span><span class="pln">hero</span><span class="pun">.</span><span class="pln">id</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><a id="always-subscribe"></a><p translation-result="on"><strong>别忘了<em>订阅</em>！</strong></p><p translation-origin="off"><strong>Always <em>subscribe</em>!</strong></p><p translation-result="on">在调用方法返回的可观察对象的 <code>subscribe()</code> 方法之前，<code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 方法不会发起 HTTP 请求。这适用于 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 的<em>所有方法</em>。</p><p translation-origin="off">An <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> method does not begin its HTTP request until you call <code>subscribe()</code> on the observable returned by that method. This is true for <em>all</em> <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> <em>methods</em>.</p><div class="alert is-helpful"><p translation-result="on"><a href="api/common/AsyncPipe"><code>AsyncPipe</code></a>会自动为你订阅（以及取消订阅）。</p><p translation-origin="off">The <a href="api/common/AsyncPipe"><code>AsyncPipe</code></a>subscribes (and unsubscribes) for you automatically.</p></div><p translation-result="on"><code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 的所有方法返回的可观察对象都设计为<em>冷的</em>。 HTTP 请求的执行都是<em>延期执行的</em>，让你可以用 <code>tap</code> 和 <code>catchError</code> 这样的操作符来在实际执行什么之前，先对这个可观察对象进行扩展。</p><p translation-origin="off">All observables returned from <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> methods are <em>cold</em> by design. Execution of the HTTP request is <em>deferred</em>, allowing you to extend the observable with additional operations such as <code>tap</code> and <code>catchError</code> before anything actually happens.</p><p translation-result="on">调用 <code>subscribe(...)</code> 会触发这个可观察对象的执行，并导致 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 组合并把 HTTP 请求发给服务器。</p><p translation-origin="off">Calling <code>subscribe(...)</code> triggers execution of the observable and causes <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> to compose and send the HTTP request to the server.</p><p translation-result="on">你可以把这些可观察对象看做实际 HTTP 请求的<em>蓝图</em>。</p><p translation-origin="off">You can think of these observables as <em>blueprints</em> for actual HTTP requests.</p><div class="alert is-helpful"><p translation-result="on">实际上，每个 <code>subscribe()</code> 都会初始化此可观察对象的一次单独的、独立的执行。 订阅两次就会导致发起两个 HTTP 请求。</p><p translation-origin="off">In fact, each <code>subscribe()</code> initiates a separate, independent execution of the observable. Subscribing twice results in two HTTP requests.</p><code-example language="javascript" ng-version="7.0.0"><div style="display:none">const req = http.get&lt;Heroes&gt;('/api/heroes'); // 0 requests made - .subscribe() not called. req.subscribe(); // 1 request made. req.subscribe(); // 2 requests made.</div><aio-code><pre class="prettyprint lang-javascript">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">const</span><span class="pln"> req </span><span class="pun">=</span><span class="pln"> http</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">&lt;</span><span class="typ">Heroes</span><span class="pun">&gt;(</span><span class="str">'/api/heroes'</span><span class="pun">);</span><span class="pln">
</span><span class="com">// 0 requests made - .subscribe() not called.</span><span class="pln">
req</span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">();</span><span class="pln">
</span><span class="com">// 1 request made.</span><span class="pln">
req</span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">();</span><span class="pln">
</span><span class="com">// 2 requests made.</span></code>
    </pre></aio-code></code-example></div><h3 id="making-a-put-request" translation-result="on">发起 PUT 请求<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#making-a-put-request"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="making-a-put-request">Making a PUT request<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#making-a-put-request"><i class="material-icons">link</i></a></h3><p translation-result="on">应用可以发送 PUT 请求，来使用修改后的数据完全替换掉一个资源。 下面的 <code>HeroesService</code> 例子和 POST 的例子很像。</p><p translation-origin="off">An app will send a PUT request to completely replace a resource with updated data. The following <code>HeroesService</code> example is just like the POST example.</p><code-example path="http/src/app/heroes/heroes.service.ts" region="updateHero" header="app/heroes/heroes.service.ts (updateHero)" linenums="false" ng-version="7.0.0"><div style="display:none">/** PUT: <a href="api/forms/NgModel#update" class="code-anchor">update</a> the hero on the server. Returns the updated hero upon success. */ updateHero (hero: Hero): Observable&lt;Hero&gt; { return this.http.put&lt;Hero&gt;(this.heroesUrl, hero, httpOptions) .pipe( catchError(this.handleError('updateHero', hero)) ); }</div><header class="ng-star-inserted">app/heroes/heroes.service.ts (updateHero)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/heroes/heroes.service.ts (updateHero)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">/** PUT: </span><a href="api/forms/NgModel#update" class="code-anchor"><span class="com">update</span></a><span class="com"> the hero on the server. Returns the updated hero upon success. */</span><span class="pln">
updateHero </span><span class="pun">(</span><span class="pln">hero</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Hero</span><span class="pun">):</span><span class="pln"> </span><span class="typ">Observable</span><span class="pun">&lt;</span><span class="typ">Hero</span><span class="pun">&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">http</span><span class="pun">.</span><span class="pln">put</span><span class="pun">&lt;</span><span class="typ">Hero</span><span class="pun">&gt;(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">heroesUrl</span><span class="pun">,</span><span class="pln"> hero</span><span class="pun">,</span><span class="pln"> httpOptions</span><span class="pun">)</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">pipe</span><span class="pun">(</span><span class="pln">
      catchError</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">handleError</span><span class="pun">(</span><span class="str">'updateHero'</span><span class="pun">,</span><span class="pln"> hero</span><span class="pun">))</span><span class="pln">
    </span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">因为<a href="guide/http#always-subscribe">前面解释过的</a>原因，调用者（这里是 <code>HeroesComponent.update()</code>）必须 <code>subscribe()</code> 由 <code><a href="api/common/http/HttpClient#put" class="code-anchor">HttpClient.put()</a></code> 返回的可观察对象，以发起这个调用。</p><p translation-origin="off">For the reasons <a href="guide/http#always-subscribe">explained above</a>, the caller (<code>HeroesComponent.update()</code> in this case) must <code>subscribe()</code> to the observable returned from the <code><a href="api/common/http/HttpClient#put" class="code-anchor">HttpClient.put()</a></code> in order to initiate the request.</p><h2 id="advanced-usage" translation-result="on">高级用法<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#advanced-usage"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="advanced-usage">Advanced usage<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#advanced-usage"><i class="material-icons">link</i></a></h2><p translation-result="on">我们已经讨论了 <code>@angular/common/<a href="api/common/http" class="code-anchor">http</a></code> 的基本 HTTP 功能，但有时候除了单纯发起请求和取回数据之外，你还要再做点别的。</p><p translation-origin="off">We have discussed the basic HTTP functionality in <code>@angular/common/<a href="api/common/http" class="code-anchor">http</a></code>, but sometimes you need to do more than make simple requests and get data back.</p><h3 id="configuring-the-request" translation-result="on">配置请求<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#configuring-the-request"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="configuring-the-request">Configuring the request<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#configuring-the-request"><i class="material-icons">link</i></a></h3><p translation-result="on">待发送请求的其它方面可以通过传给 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 方法的最后一个参数指定的配置对象进行配置。</p><p translation-origin="off">Other aspects of an outgoing request can be configured via the options object passed as the last argument to the <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> method.</p><p translation-result="on"><a href="guide/http#adding-headers">以前你曾在</a> <code>HeroesService</code> 中通过在其保存方法中传入配置对象 <code>httpOptions</code> 设置过默认头。 你还可以做更多。</p><p translation-origin="off">You <a href="guide/http#adding-headers">saw earlier</a> that the <code>HeroesService</code> sets the default headers by passing an options object (<code>httpOptions</code>) to its save methods. You can do more.</p><h4 id="update-headers" translation-result="on">修改这些头<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#update-headers"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="update-headers">Update headers<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#update-headers"><i class="material-icons">link</i></a></h4><p translation-result="on">你没法直接修改前述配置对象中的现有头，因为这个 <code><a href="api/common/http/HttpHeaders" class="code-anchor">HttpHeaders</a></code> 类的实例是不可变的。</p><p translation-origin="off">You can't directly modify the existing headers within the previous options object because instances of the <code><a href="api/common/http/HttpHeaders" class="code-anchor">HttpHeaders</a></code> class are immutable.</p><p translation-result="on">改用 <code>set()</code> 方法代替。 它会返回当前实例的一份克隆，其中应用了这些新修改。</p><p translation-origin="off">Use the <code>set()</code> method instead. It returns a clone of the current instance with the new changes applied.</p><p translation-result="on">比如在发起下一个请求之前，如果旧的令牌已经过期了，你可能还要修改认证头。</p><p translation-origin="off">Here's how you might update the authorization header (after the old token expired) before making the next request.</p><code-example path="http/src/app/heroes/heroes.service.ts" region="update-headers" linenums="false" ng-version="7.0.0"><div style="display:none">httpOptions.headers = httpOptions.headers.set('Authorization', 'my-new-auth-token');</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">httpOptions</span><span class="pun">.</span><span class="pln">headers </span><span class="pun">=</span><span class="pln">
  httpOptions</span><span class="pun">.</span><span class="pln">headers</span><span class="pun">.</span><span class="kwd">set</span><span class="pun">(</span><span class="str">'Authorization'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'my-new-auth-token'</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><h4 id="url-parameters" translation-result="on">URL 参数<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#url-parameters"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="url-parameters">URL Parameters<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#url-parameters"><i class="material-icons">link</i></a></h4><p translation-result="on">添加 URL 搜索参数也与此类似。 这里的 <code>searchHeroes</code> 方法会查询名字中包含搜索词的英雄列表。</p><p translation-origin="off">Adding URL search parameters works a similar way. Here is a <code>searchHeroes</code> method that queries for heroes whose names contain the search term.</p><code-example path="http/src/app/heroes/heroes.service.ts" region="searchHeroes" linenums="false" ng-version="7.0.0"><div style="display:none">/* GET heroes whose name contains <a href="api/common/PlatformLocation#search" class="code-anchor">search</a> term */ searchHeroes(term: string): Observable&lt;Hero[]&gt; { term = term.trim(); // Add safe, <a href="api/core/SecurityContext#URL" class="code-anchor">URL</a> encoded <a href="api/common/PlatformLocation#search" class="code-anchor">search</a> parameter if there is <a href="api/router/RouterLinkWithHref" class="code-anchor">a</a> <a href="api/common/PlatformLocation#search" class="code-anchor">search</a> term const options = term ? { params: new <a href="api/common/http/HttpParams" class="code-anchor">HttpParams</a>().set('name', term) } : {}; return this.http.get&lt;Hero[]&gt;(this.heroesUrl, options) .pipe( catchError(this.handleError&lt;Hero[]&gt;('searchHeroes', [])) ); }</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">/* GET heroes whose name contains </span><a href="api/common/PlatformLocation#search" class="code-anchor"><span class="com">search</span></a><span class="com"> term */</span><span class="pln">
searchHeroes</span><span class="pun">(</span><span class="pln">term</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">string</span><span class="pun">):</span><span class="pln"> </span><span class="typ">Observable</span><span class="pun">&lt;</span><span class="typ">Hero</span><span class="pun">[]&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  term </span><span class="pun">=</span><span class="pln"> term</span><span class="pun">.</span><span class="pln">trim</span><span class="pun">();</span><span class="pln">

  </span><span class="com">// Add safe, </span><a href="api/core/SecurityContext#URL" class="code-anchor"><span class="com">URL</span></a><span class="com"> encoded </span><a href="api/common/PlatformLocation#search" class="code-anchor"><span class="com">search</span></a><span class="com"> parameter if there is </span><a href="api/router/RouterLinkWithHref" class="code-anchor"><span class="com">a</span></a><span class="com"> </span><a href="api/common/PlatformLocation#search" class="code-anchor"><span class="com">search</span></a><span class="com"> term</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> options </span><span class="pun">=</span><span class="pln"> term </span><span class="pun">?</span><span class="pln">
   </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">params</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><a href="api/common/http/HttpParams" class="code-anchor"><span class="typ">HttpParams</span></a><span class="pun">().</span><span class="kwd">set</span><span class="pun">(</span><span class="str">'name'</span><span class="pun">,</span><span class="pln"> term</span><span class="pun">)</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">:</span><span class="pln"> </span><span class="pun">{};</span><span class="pln">

  </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">http</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">&lt;</span><span class="typ">Hero</span><span class="pun">[]&gt;(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">heroesUrl</span><span class="pun">,</span><span class="pln"> options</span><span class="pun">)</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">pipe</span><span class="pun">(</span><span class="pln">
      catchError</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">handleError</span><span class="pun">&lt;</span><span class="typ">Hero</span><span class="pun">[]&gt;(</span><span class="str">'searchHeroes'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">[]))</span><span class="pln">
    </span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">如果有搜索词，这段代码就会构造一个包含进行过 URL 编码的搜索词的选项对象。如果这个搜索词是“foo”，这个 GET 请求的 URL 就会是 <code>api/heroes/?name=foo</code>。</p><p translation-origin="off">If there is a search term, the code constructs an options object with an HTML URL-encoded search parameter. If the term were "foo", the GET request URL would be <code>api/heroes/?name=foo</code>.</p><p translation-result="on"><code><a href="api/common/http/HttpParams" class="code-anchor">HttpParams</a></code> 是不可变的，所以你也要使用 <code>set()</code> 方法来修改这些选项。</p><p translation-origin="off">The <code><a href="api/common/http/HttpParams" class="code-anchor">HttpParams</a></code> are immutable so you'll have to use the <code>set()</code> method to update the options.</p><h3 id="debouncing-requests" translation-result="on">请求的防抖（debounce）<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#debouncing-requests"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="debouncing-requests">Debouncing requests<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#debouncing-requests"><i class="material-icons">link</i></a></h3><p translation-result="on">这个例子还包含了<em>搜索 npm 包</em>的特性。</p><p translation-origin="off">The sample includes an <em>npm package search</em> feature.</p><p translation-result="on">当用户在搜索框中输入名字时，<code>PackageSearchComponent</code> 就会把一个根据名字搜索包的请求发送给 NPM 的 web api。</p><p translation-origin="off">When the user enters a name in a search-box, the <code>PackageSearchComponent</code> sends a search request for a package with that name to the NPM web API.</p><p translation-result="on">下面是模板中的相关代码片段：</p><p translation-origin="off">Here's a pertinent excerpt from the template:</p><code-example path="http/src/app/package-search/package-search.component.html" region="search" header="app/package-search/package-search.component.html (search)" ng-version="7.0.0"><div style="display:none">&lt;input (keyup)="<a href="api/common/PlatformLocation#search" class="code-anchor">search</a>($event.target.value)" id="name" placeholder="Search"/&gt; &lt;ul&gt; &lt;li *<a href="api/common/NgForOf" class="code-anchor">ngFor</a>="let package of packages$ | <a href="api/core/testing/async" class="code-anchor">async</a>"&gt; &lt;b&gt;{{package.name}} v.{{package.version}}&lt;/b&gt; - &lt;i&gt;{{package.description}}&lt;/i&gt; &lt;/li&gt; &lt;/ul&gt;</div><header class="ng-star-inserted">app/package-search/package-search.component.html (search)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/package-search/package-search.component.html (search)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="tag">&lt;input</span><span class="pln"> (</span><span class="atn">keyup</span><span class="pln">)</span><span class="pun">=</span><span class="atv">"</span><a href="api/common/PlatformLocation#search" class="code-anchor"><span class="atv">search</span></a><span class="atv">($event.target.value)"</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"name"</span><span class="pln"> </span><span class="atn">placeholder</span><span class="pun">=</span><span class="atv">"Search"</span><span class="tag">/&gt;</span><span class="pln">

</span><span class="tag">&lt;ul&gt;</span><span class="pln">
  </span><span class="tag">&lt;li</span><span class="pln"> *</span><a href="api/common/NgForOf" class="code-anchor"><span class="atn">ngFor</span></a><span class="pun">=</span><span class="atv">"let package of packages$ | </span><a href="api/core/testing/async" class="code-anchor"><span class="atv">async</span></a><span class="atv">"</span><span class="tag">&gt;</span><span class="pln">
    </span><span class="tag">&lt;b&gt;</span><span class="pln">{{package.name}} v.{{package.version}}</span><span class="tag">&lt;/b&gt;</span><span class="pln"> -
    </span><span class="tag">&lt;i&gt;</span><span class="pln">{{package.description}}</span><span class="tag">&lt;/i&gt;</span><span class="pln">
  </span><span class="tag">&lt;/li&gt;</span><span class="pln">
</span><span class="tag">&lt;/ul&gt;</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>(keyup)</code> 事件绑定把每次击键都发送给了组件的 <code><a href="api/common/PlatformLocation#search" class="code-anchor">search</a>()</code> 方法。</p><p translation-origin="off">The <code>(keyup)</code> event binding sends every keystroke to the component's <code><a href="api/common/PlatformLocation#search" class="code-anchor">search</a>()</code> method.</p><p translation-result="on">如果每次击键都发送一次请求就太昂贵了。 最好能等到用户停止输入时才发送请求。 使用 RxJS 的操作符就能轻易实现它，参见下面的代码片段：</p><p translation-origin="off">Sending a request for every keystroke could be expensive. It's better to wait until the user stops typing and then send a request. That's easy to implement with RxJS operators, as shown in this excerpt.</p><code-example path="http/src/app/package-search/package-search.component.ts" region="debounce" header="app/package-search/package-search.component.ts (excerpt))" ng-version="7.0.0"><div style="display:none">withRefresh = false; packages$: Observable&lt;NpmPackageInfo[]&gt;; private searchText$ = new Subject&lt;string&gt;(); <a href="api/common/PlatformLocation#search" class="code-anchor">search</a>(packageName: string) { this.searchText$.next(packageName); } ngOnInit() { this.packages$ = this.searchText$.pipe( debounceTime(500), distinctUntilChanged(), switchMap(packageName =&gt; this.searchService.search(packageName, this.withRefresh)) ); } constructor(private searchService: PackageSearchService) { }</div><header class="ng-star-inserted">app/package-search/package-search.component.ts (excerpt))</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/package-search/package-search.component.ts (excerpt))">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><ol class="linenums"><li class="L0"><span class="pln">withRefresh </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">false</span><span class="pun">;</span></li><li class="L1"><span class="pln">packages$</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Observable</span><span class="pun">&lt;</span><span class="typ">NpmPackageInfo</span><span class="pun">[]&gt;;</span></li><li class="L2"><span class="kwd">private</span><span class="pln"> searchText$ </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Subject</span><span class="str">&lt;string&gt;</span><span class="pun">();</span></li><li class="L3"><span class="pln">&nbsp;</span></li><li class="L4"><a href="api/common/PlatformLocation#search" class="code-anchor"><span class="pln">search</span></a><span class="pun">(</span><span class="pln">packageName</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">string</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span></li><li class="L5"><span class="pln">  </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">searchText$</span><span class="pun">.</span><span class="kwd">next</span><span class="pun">(</span><span class="pln">packageName</span><span class="pun">);</span></li><li class="L6"><span class="pun">}</span></li><li class="L7"><span class="pln">&nbsp;</span></li><li class="L8"><span class="pln">ngOnInit</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span></li><li class="L9"><span class="pln">  </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">packages$ </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">searchText$</span><span class="pun">.</span><span class="pln">pipe</span><span class="pun">(</span></li><li class="L0"><span class="pln">    debounceTime</span><span class="pun">(</span><span class="lit">500</span><span class="pun">),</span></li><li class="L1"><span class="pln">    distinctUntilChanged</span><span class="pun">(),</span></li><li class="L2"><span class="pln">    switchMap</span><span class="pun">(</span><span class="pln">packageName </span><span class="pun">=&gt;</span></li><li class="L3"><span class="pln">      </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">searchService</span><span class="pun">.</span><span class="pln">search</span><span class="pun">(</span><span class="pln">packageName</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">withRefresh</span><span class="pun">))</span></li><li class="L4"><span class="pln">  </span><span class="pun">);</span></li><li class="L5"><span class="pun">}</span></li><li class="L6"><span class="pln">&nbsp;</span></li><li class="L7"><span class="kwd">constructor</span><span class="pun">(</span><span class="kwd">private</span><span class="pln"> searchService</span><span class="pun">:</span><span class="pln"> </span><span class="typ">PackageSearchService</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="pun">}</span></li></ol></code>
    </pre></aio-code></code-example><p translation-result="on"><code>searchText$</code> 是一个序列，包含用户输入到搜索框中的所有值。 它定义成了 RxJS 的 <code>Subject</code> 对象，这表示它是一个多播 <code>Observable</code>，同时还可以自行调用 <code>next(value)</code> 来产生值。 <code><a href="api/common/PlatformLocation#search" class="code-anchor">search</a>()</code> 方法中就是这么做的。</p><p translation-origin="off">The <code>searchText$</code> is the sequence of search-box values coming from the user. It's defined as an RxJS <code>Subject</code>, which means it is a multicasting <code>Observable</code> that can also produce values for itself by calling <code>next(value)</code>, as happens in the <code><a href="api/common/PlatformLocation#search" class="code-anchor">search</a>()</code> method.</p><p translation-result="on">除了把每个 <code>searchText</code> 的值都直接转发给 <code>PackageSearchService</code> 之外，<code>ngOnInit()</code> 中的代码还通过下列三个操作符对这些搜索值进行<em>管道</em>处理：</p><p translation-origin="off">Rather than forward every <code>searchText</code> value directly to the injected <code>PackageSearchService</code>, the code in <code>ngOnInit()</code> <em>pipes</em> search values through three operators:</p><ol><li><p translation-result="on"><code>debounceTime(500)</code> - 等待，直到用户停止输入（这个例子中是停止 1/2 秒）。</p><p translation-origin="off"><code>debounceTime(500)</code> - wait for the user to stop typing (1/2 second in this case).</p></li><li><p translation-result="on"><code>distinctUntilChanged()</code> - 等待，直到搜索内容发生了变化。</p><p translation-origin="off"><code>distinctUntilChanged()</code> - wait until the search text changes.</p></li><li><p translation-result="on"><code>switchMap()</code> - 把搜索请求发送给服务。</p><p translation-origin="off"><code>switchMap()</code> - send the search request to the service.</p></li></ol><p translation-result="on">这些代码把 <code>packages$</code> 设置成了使用搜索结果组合出的 <code>Observable</code> 对象。 模板中使用 <a href="api/common/AsyncPipe">AsyncPipe</a> 订阅了 <code>packages$</code>，一旦搜索结果的值发回来了，就显示这些搜索结果。</p><p translation-origin="off">The code sets <code>packages$</code> to this re-composed <code>Observable</code> of search results. The template subscribes to <code>packages$</code> with the <a href="api/common/AsyncPipe">AsyncPipe</a> and displays search results as they arrive.</p><p translation-result="on">这样，只有当用户停止了输入且搜索值和以前不一样的时候，搜索值才会传给服务。</p><p translation-origin="off">A search value reaches the service only if it's a new value and the user has stopped typing.</p><div class="alert is-helpful"><p translation-result="on"><a href="guide/http#cache-refresh">稍后</a> 解释了这个 <code>withRefresh</code> 选项。</p><p translation-origin="off">The <code>withRefresh</code> option is explained <a href="guide/http#cache-refresh">below</a>.</p></div><h4 id="switchmap"><em>switchMap()</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#switchmap"><i class="material-icons">link</i></a></h4><p translation-result="on">这个 <code>switchMap()</code> 操作符有三个重要的特征：</p><p translation-origin="off">The <code>switchMap()</code> operator has three important characteristics.</p><ol><li><p translation-result="on">它的参数是一个返回 <code>Observable</code> 的函数。<code>PackageSearchService.search</code> 会返回 <code>Observable</code>，其它数据服务也一样。</p><p translation-origin="off">It takes a function argument that returns an <code>Observable</code>. <code>PackageSearchService.search</code> returns an <code>Observable</code>, as other data service methods do.</p></li><li><p translation-result="on">如果以前的搜索结果仍然是<em>在途</em>状态（这会出现在慢速网络中），它会取消那个请求，并发起一次新的搜索。</p><p translation-origin="off">If a previous search request is still <em>in-flight</em> (as when the connection is poor), it cancels that request and sends a new one.</p></li><li><p translation-result="on">它会按照原始的请求顺序返回这些服务的响应，而不用关心服务器实际上是以乱序返回的它们。</p><p translation-origin="off">It returns service responses in their original request order, even if the server returns them out of order.</p></li></ol><div class="alert is-helpful"><p translation-result="on">如果你觉得将来会复用这些防抖逻辑， 可以把它移到单独的工具函数中，或者移到 <code>PackageSearchService</code> 中。</p><p translation-origin="off">If you think you'll reuse this debouncing logic, consider moving it to a utility function or into the <code>PackageSearchService</code> itself.</p></div><h3 id="intercepting-requests-and-responses" translation-result="on">拦截请求和响应<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#intercepting-requests-and-responses"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="intercepting-requests-and-responses">Intercepting requests and responses<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#intercepting-requests-and-responses"><i class="material-icons">link</i></a></h3><p translation-result="on"><em>HTTP</em> 拦截机制是 <code>@angular/common/<a href="api/common/http" class="code-anchor">http</a></code> 中的主要特性之一。 使用这种拦截机制，你可以声明<em>一些拦截器</em>，用它们监视和转换从应用发送到服务器的 HTTP 请求。 拦截器还可以用监视和转换从服务器返回到本应用的那些响应。 多个选择器会构成一个“请求/响应处理器”的双向链表。</p><p translation-origin="off"><em>HTTP Interception</em> is a major feature of <code>@angular/common/<a href="api/common/http" class="code-anchor">http</a></code>. With interception, you declare <em>interceptors</em> that inspect and transform HTTP requests from your application to the server. The same interceptors may also inspect and transform the server's responses on their way back to the application. Multiple interceptors form a <em>forward-and-backward</em> chain of request/response handlers.</p><p translation-result="on">拦截器可以用一种常规的、标准的方式对每一次 HTTP 的请求/响应任务执行从认证到记日志等很多种<em>隐式</em>任务。</p><p translation-origin="off">Interceptors can perform a variety of <em>implicit</em> tasks, from authentication to logging, in a routine, standard way, for every HTTP request/response.</p><p translation-result="on">如果没有拦截机制，那么开发人员将不得不对每次 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 调用<em>显式</em>实现这些任务。</p><p translation-origin="off">Without interception, developers would have to implement these tasks <em>explicitly</em> for each <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> method call.</p><h4 id="write-an-interceptor" translation-result="on">编写拦截器<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#write-an-interceptor"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="write-an-interceptor">Write an interceptor<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#write-an-interceptor"><i class="material-icons">link</i></a></h4><p translation-result="on">要实现拦截器，就要实现一个实现了 <code><a href="api/common/http/HttpInterceptor" class="code-anchor">HttpInterceptor</a></code> 接口中的 <code><a href="api/common/http/JsonpInterceptor#intercept" class="code-anchor">intercept()</a></code> 方法的类。</p><p translation-origin="off">To implement an interceptor, declare a class that implements the <code><a href="api/common/http/JsonpInterceptor#intercept" class="code-anchor">intercept()</a></code> method of the <code><a href="api/common/http/HttpInterceptor" class="code-anchor">HttpInterceptor</a></code> interface.</p><p translation-result="on">这里是一个什么也不做的<em>空白</em>拦截器，它只会不做任何修改的传递这个请求。</p><p translation-origin="off">Here is a do-nothing <em>noop</em> interceptor that simply passes the request through without touching it:</p><code-example path="http/src/app/http-interceptors/noop-interceptor.ts" header="app/http-interceptors/noop-interceptor.ts" linenums="false" ng-version="7.0.0"><div style="display:none">import { <a href="api/core/Injectable" class="code-anchor">Injectable</a> } from '@angular/core'; import { <a href="api/common/http/HttpEvent" class="code-anchor">HttpEvent</a>, <a href="api/common/http/HttpInterceptor" class="code-anchor">HttpInterceptor</a>, <a href="api/common/http/HttpHandler" class="code-anchor">HttpHandler</a>, <a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a> } from '@angular/common/<a href="api/common/http" class="code-anchor">http</a>'; import { Observable } from 'rxjs'; /** Pass untouched request through to the next request handler. */ @<a href="api/core/Injectable" class="code-anchor">Injectable</a>() export class NoopInterceptor implements <a href="api/common/http/HttpInterceptor" class="code-anchor">HttpInterceptor</a> { intercept(req: <a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a>&lt;any&gt;, next: <a href="api/common/http/HttpHandler" class="code-anchor">HttpHandler</a>): Observable&lt;<a href="api/common/http/HttpEvent" class="code-anchor">HttpEvent</a>&lt;any&gt;&gt; { return next.handle(req); } }</div><header class="ng-star-inserted">app/http-interceptors/noop-interceptor.ts</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/http-interceptors/noop-interceptor.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/Injectable" class="code-anchor"><span class="typ">Injectable</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core'</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><a href="api/common/http/HttpEvent" class="code-anchor"><span class="typ">HttpEvent</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/common/http/HttpInterceptor" class="code-anchor"><span class="typ">HttpInterceptor</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/common/http/HttpHandler" class="code-anchor"><span class="typ">HttpHandler</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/common/http/HttpRequest" class="code-anchor"><span class="typ">HttpRequest</span></a><span class="pln">
</span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/common/</span><a href="api/common/http" class="code-anchor"><span class="str">http</span></a><span class="str">'</span><span class="pun">;</span><span class="pln">

</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">Observable</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'rxjs'</span><span class="pun">;</span><span class="pln">

</span><span class="com">/** Pass untouched request through to the next request handler. */</span><span class="pln">
</span><span class="lit">@</span><a href="api/core/Injectable" class="code-anchor"><span class="lit">Injectable</span></a><span class="pun">()</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">NoopInterceptor</span><span class="pln"> </span><span class="kwd">implements</span><span class="pln"> </span><a href="api/common/http/HttpInterceptor" class="code-anchor"><span class="typ">HttpInterceptor</span></a><span class="pln"> </span><span class="pun">{</span><span class="pln">

  intercept</span><span class="pun">(</span><span class="pln">req</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpRequest" class="code-anchor"><span class="typ">HttpRequest</span></a><span class="str">&lt;any&gt;</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpHandler" class="code-anchor"><span class="typ">HttpHandler</span></a><span class="pun">):</span><span class="pln">
    </span><span class="typ">Observable</span><span class="pun">&lt;</span><a href="api/common/http/HttpEvent" class="code-anchor"><span class="typ">HttpEvent</span></a><span class="str">&lt;any&gt;</span><span class="pun">&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">.</span><span class="pln">handle</span><span class="pun">(</span><span class="pln">req</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>intercept</code> 方法会把请求转换成一个最终返回 HTTP 响应体的 <code>Observable</code>。 在这个场景中，每个拦截器都完全能自己处理这个请求。</p><p translation-origin="off">The <code>intercept</code> method transforms a request into an <code>Observable</code> that eventually returns the HTTP response. In this sense, each interceptor is fully capable of handling the request entirely by itself.</p><p translation-result="on">大多数拦截器拦截都会在传入时检查请求，然后把（可能被修改过的）请求转发给 <code>next</code> 对象的 <code>handle()</code> 方法，而 <code>next</code> 对象实现了 <a href="api/common/http/HttpHandler"><code>HttpHandler</code></a>接口。</p><p translation-origin="off">Most interceptors inspect the request on the way in and forward the (perhaps altered) request to the <code>handle()</code> method of the <code>next</code> object which implements the <a href="api/common/http/HttpHandler"><code>HttpHandler</code></a>interface.</p><code-example language="javascript" ng-version="7.0.0"><div style="display:none">export abstract class <a href="api/common/http/HttpHandler" class="code-anchor">HttpHandler</a> { abstract handle(req: <a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a>&lt;any&gt;): Observable&lt;<a href="api/common/http/HttpEvent" class="code-anchor">HttpEvent</a>&lt;any&gt;&gt;; }</div><aio-code><pre class="prettyprint lang-javascript">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">export</span><span class="pln"> </span><span class="kwd">abstract</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><a href="api/common/http/HttpHandler" class="code-anchor"><span class="typ">HttpHandler</span></a><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">abstract</span><span class="pln"> handle</span><span class="pun">(</span><span class="pln">req</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpRequest" class="code-anchor"><span class="typ">HttpRequest</span></a><span class="pun">&lt;</span><span class="pln">any</span><span class="pun">&gt;):</span><span class="pln"> </span><span class="typ">Observable</span><span class="pun">&lt;</span><a href="api/common/http/HttpEvent" class="code-anchor"><span class="typ">HttpEvent</span></a><span class="pun">&lt;</span><span class="pln">any</span><span class="pun">&gt;&gt;;</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on">像 <code><a href="api/common/http/JsonpInterceptor#intercept" class="code-anchor">intercept()</a></code> 一样，<code>handle()</code> 方法也会把 HTTP 请求转换成 <a href="guide/http#httpevents"><code>HttpEvents</code></a>组成的 <code>Observable</code>，它最终包含的是来自服务器的响应。 <code><a href="api/common/http/JsonpInterceptor#intercept" class="code-anchor">intercept()</a></code> 函数可以检查这个可观察对象，并在把它返回给调用者之前修改它。</p><p translation-origin="off">Like <code><a href="api/common/http/JsonpInterceptor#intercept" class="code-anchor">intercept()</a></code>, the <code>handle()</code> method transforms an HTTP request into an <code>Observable</code> of <a href="guide/http#httpevents"><code>HttpEvents</code></a>which ultimately include the server's response. The <code><a href="api/common/http/JsonpInterceptor#intercept" class="code-anchor">intercept()</a></code> method could inspect that observable and alter it before returning it to the caller.</p><p translation-result="on">这个<em>无操作的</em>拦截器，会直接使用原始的请求调用 <code>next.handle()</code>，并返回它返回的可观察对象，而不做任何后续处理。</p><p translation-origin="off">This <em>no-op</em> interceptor simply calls <code>next.handle()</code> with the original request and returns the observable without doing a thing.</p><h4 id="the-next-object" translation-result="on"><code>next</code> 对象<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#the-next-object"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="the-next-object">The <em>next</em> object<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#the-next-object"><i class="material-icons">link</i></a></h4><p translation-result="on"><code>next</code> 对象表示拦截器链表中的下一个拦截器。 这个链表中的最后一个 <code>next</code> 对象就是 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 的后端处理器（backend handler），它会把请求发给服务器，并接收服务器的响应。</p><p translation-origin="off">The <code>next</code> object represents the next interceptor in the chain of interceptors. The final <code>next</code> in the chain is the <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> backend handler that sends the request to the server and receives the server's response.</p><p translation-result="on">大多数的拦截器都会调用 <code>next.handle()</code>，以便这个请求流能走到下一个拦截器，并最终传给后端处理器。 拦截器也<em>可以</em>不调用 <code>next.handle()</code>，使这个链路短路，并返回一个带有人工构造出来的服务器响应的 <a href="guide/http#caching">自己的 <code>Observable</code></a>。</p><p translation-origin="off">Most interceptors call <code>next.handle()</code> so that the request flows through to the next interceptor and, eventually, the backend handler. An interceptor <em>could</em> skip calling <code>next.handle()</code>, short-circuit the chain, and <a href="guide/http#caching">return its own <code>Observable</code></a>with an artificial server response.</p><p translation-result="on">这是一种常见的中间件模式，在像 Express.js 这样的框架中也会找到它。</p><p translation-origin="off">This is a common middleware pattern found in frameworks such as Express.js.</p><h4 id="provide-the-interceptor" translation-result="on">提供这个拦截器<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#provide-the-interceptor"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="provide-the-interceptor">Provide the interceptor<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#provide-the-interceptor"><i class="material-icons">link</i></a></h4><p translation-result="on">这个 <code>NoopInterceptor</code> 就是一个由 Angular <a href="guide/dependency-injection">依赖注入 (DI)</a>系统管理的服务。 像其它服务一样，你也必须先提供这个拦截器类，应用才能使用它。</p><p translation-origin="off">The <code>NoopInterceptor</code> is a service managed by Angular's <a href="guide/dependency-injection">dependency injection (DI)</a> system. Like other services, you must provide the interceptor class before the app can use it.</p><p translation-result="on">由于拦截器是 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 服务的（可选）依赖，所以你必须在提供 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 的同一个（或其各级父注入器）注入器中提供这些拦截器。 那些在 DI 创建完 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> <em>之后</em>再提供的拦截器将会被忽略。</p><p translation-origin="off">Because interceptors are (optional) dependencies of the <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> service, you must provide them in the same injector (or a parent of the injector) that provides <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code>. Interceptors provided <em>after</em> DI creates the <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> are ignored.</p><p translation-result="on">由于在 <code>AppModule</code> 中导入了 <code><a href="api/common/http/HttpClientModule" class="code-anchor">HttpClientModule</a></code>，导致本应用在其根注入器中提供了 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code>。所以你也同样要在 <code>AppModule</code> 中提供这些拦截器。</p><p translation-origin="off">This app provides <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> in the app's root injector, as a side-effect of importing the <code><a href="api/common/http/HttpClientModule" class="code-anchor">HttpClientModule</a></code> in <code>AppModule</code>. You should provide interceptors in <code>AppModule</code> as well.</p><p translation-result="on">在从 <code>@angular/common/<a href="api/common/http" class="code-anchor">http</a></code> 中导入了 <code><a href="api/common/http/HTTP_INTERCEPTORS" class="code-anchor">HTTP_INTERCEPTORS</a></code> 注入令牌之后，编写如下的 <code>NoopInterceptor</code> 提供商注册语句：</p><p translation-origin="off">After importing the <code><a href="api/common/http/HTTP_INTERCEPTORS" class="code-anchor">HTTP_INTERCEPTORS</a></code> injection token from <code>@angular/common/<a href="api/common/http" class="code-anchor">http</a></code>, write the <code>NoopInterceptor</code> provider like this:</p><code-example path="http/src/app/http-interceptors/index.ts" region="noop-provider" linenums="false" ng-version="7.0.0"><div style="display:none">{ provide: <a href="api/common/http/HTTP_INTERCEPTORS" class="code-anchor">HTTP_INTERCEPTORS</a>, useClass: NoopInterceptor, multi: true },</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HTTP_INTERCEPTORS" class="code-anchor"><span class="pln">HTTP_INTERCEPTORS</span></a><span class="pun">,</span><span class="pln"> useClass</span><span class="pun">:</span><span class="pln"> </span><span class="typ">NoopInterceptor</span><span class="pun">,</span><span class="pln"> multi</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">true</span><span class="pln"> </span><span class="pun">},</span></code>
    </pre></aio-code></code-example><p translation-result="on">注意 <code>multi: true</code> 选项。 这个必须的选项会告诉 Angular <code><a href="api/common/http/HTTP_INTERCEPTORS" class="code-anchor">HTTP_INTERCEPTORS</a></code> 是一个<em>多重提供商</em>的令牌，表示它会注入一个多值的数组，而不是单一的值。</p><p translation-origin="off">Note the <code>multi: true</code> option. This required setting tells Angular that <code><a href="api/common/http/HTTP_INTERCEPTORS" class="code-anchor">HTTP_INTERCEPTORS</a></code> is a token for a <em>multiprovider</em> that injects an array of values, rather than a single value.</p><p translation-result="on">你<em>也可以</em>直接把这个提供商添加到 <code>AppModule</code> 中的提供商数组中，不过那样会非常啰嗦。况且，你将来还会用这种方式创建更多的拦截器并提供它们。 你还要<a href="guide/http#interceptor-order">特别注意提供这些拦截器的顺序</a>。</p><p translation-origin="off">You <em>could</em> add this provider directly to the providers array of the <code>AppModule</code>. However, it's rather verbose and there's a good chance that you'll create more interceptors and provide them in the same way. You must also pay <a href="guide/http#interceptor-order">close attention to the order</a> in which you provide these interceptors.</p><p translation-result="on">认真考虑创建一个封装桶（barrel）文件，用于把所有拦截器都收集起来，一起提供给 <code>httpInterceptorProviders</code> 数组，可以先从这个 <code>NoopInterceptor</code> 开始。</p><p translation-origin="off">Consider creating a "barrel" file that gathers all the interceptor providers into an <code>httpInterceptorProviders</code> array, starting with this first one, the <code>NoopInterceptor</code>.</p><code-example path="http/src/app/http-interceptors/index.ts" region="interceptor-providers" header="app/http-interceptors/index.ts" linenums="false" ng-version="7.0.0"><div style="display:none">/* "Barrel" of <a href="api/http/Http" class="code-anchor">Http</a> Interceptors */ import { <a href="api/common/http/HTTP_INTERCEPTORS" class="code-anchor">HTTP_INTERCEPTORS</a> } from '@angular/common/<a href="api/common/http" class="code-anchor">http</a>'; import { NoopInterceptor } from './noop-interceptor'; /** <a href="api/http/Http" class="code-anchor">Http</a> interceptor providers in outside-in order */ export const httpInterceptorProviders = [ { provide: <a href="api/common/http/HTTP_INTERCEPTORS" class="code-anchor">HTTP_INTERCEPTORS</a>, useClass: NoopInterceptor, multi: true }, ];</div><header class="ng-star-inserted">app/http-interceptors/index.ts</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/http-interceptors/index.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">/* "Barrel" of </span><a href="api/http/Http" class="code-anchor"><span class="com">Http</span></a><span class="com"> Interceptors */</span><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/common/http/HTTP_INTERCEPTORS" class="code-anchor"><span class="pln">HTTP_INTERCEPTORS</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/common/</span><a href="api/common/http" class="code-anchor"><span class="str">http</span></a><span class="str">'</span><span class="pun">;</span><span class="pln">

</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">NoopInterceptor</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'./noop-interceptor'</span><span class="pun">;</span><span class="pln">

</span><span class="com">/** </span><a href="api/http/Http" class="code-anchor"><span class="com">Http</span></a><span class="com"> interceptor providers in outside-in order */</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">const</span><span class="pln"> httpInterceptorProviders </span><span class="pun">=</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
  </span><span class="pun">{</span><span class="pln"> provide</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HTTP_INTERCEPTORS" class="code-anchor"><span class="pln">HTTP_INTERCEPTORS</span></a><span class="pun">,</span><span class="pln"> useClass</span><span class="pun">:</span><span class="pln"> </span><span class="typ">NoopInterceptor</span><span class="pun">,</span><span class="pln"> multi</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">true</span><span class="pln"> </span><span class="pun">},</span><span class="pln">
</span><span class="pun">];</span></code>
    </pre></aio-code></code-example><p translation-result="on">然后导入它，并把它加到 <code>AppModule</code> 的 <em><code>providers</code> 数组</em>中，就像这样：</p><p translation-origin="off">Then import and add it to the <code>AppModule</code> <em>providers array</em> like this:</p><code-example path="http/src/app/app.module.ts" region="interceptor-providers" header="app/app.module.ts (interceptor providers)" linenums="false" ng-version="7.0.0"><div style="display:none">providers: [ httpInterceptorProviders ],</div><header class="ng-star-inserted">app/app.module.ts (interceptor providers)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/app.module.ts (interceptor providers)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">providers</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
  httpInterceptorProviders
</span><span class="pun">],</span></code>
    </pre></aio-code></code-example><p translation-result="on">当你再创建新的拦截器时，就同样把它们添加到 <code>httpInterceptorProviders</code> 数组中，而不用再修改 <code>AppModule</code>。</p><p translation-origin="off">As you create new interceptors, add them to the <code>httpInterceptorProviders</code> array and you won't have to revisit the <code>AppModule</code>.</p><div class="alert is-helpful"><p translation-result="on">在完整版的范例代码中还有更多的拦截器。</p><p translation-origin="off">There are many more interceptors in the complete sample code.</p></div><h4 id="interceptor-order" translation-result="on">拦截器的顺序<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#interceptor-order"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="interceptor-order">Interceptor order<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#interceptor-order"><i class="material-icons">link</i></a></h4><p translation-result="on">Angular 会按照你提供它们的顺序应用这些拦截器。 如果你提供拦截器的顺序是先 <em>A</em>，再 <em>B</em>，再 <em>C</em>，那么请求阶段的执行顺序就是 <em>A-&gt;B-&gt;C</em>，而响应阶段的执行顺序则是 <em>C-&gt;B-&gt;A</em>。</p><p translation-origin="off">Angular applies interceptors in the order that you provide them. If you provide interceptors <em>A</em>, then <em>B</em>, then <em>C</em>, requests will flow in <em>A-&gt;B-&gt;C</em> and responses will flow out <em>C-&gt;B-&gt;A</em>.</p><p translation-result="on">以后你就再也不能修改这些顺序或移除某些拦截器了。 如果你需要动态启用或禁用某个拦截器，那就要在那个拦截器中自行实现这个功能。</p><p translation-origin="off">You cannot change the order or remove interceptors later. If you need to enable and disable an interceptor dynamically, you'll have to build that capability into the interceptor itself.</p><h4 id="httpevents"><em>HttpEvents</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#httpevents"><i class="material-icons">link</i></a></h4><p translation-result="on">你可能会期望 <code><a href="api/common/http/JsonpInterceptor#intercept" class="code-anchor">intercept()</a></code> 和 <code>handle()</code> 方法会像大多数 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 中的方法那样返回 <code><a href="api/common/http/HttpResponse" class="code-anchor">HttpResponse</a>&lt;any&gt;</code> 的可观察对象。</p><p translation-origin="off">You may have expected the <code><a href="api/common/http/JsonpInterceptor#intercept" class="code-anchor">intercept()</a></code> and <code>handle()</code> methods to return observables of <code><a href="api/common/http/HttpResponse" class="code-anchor">HttpResponse</a>&lt;any&gt;</code> as most <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> methods do.</p><p translation-result="on">然而并没有，它们返回的是 <code><a href="api/common/http/HttpEvent" class="code-anchor">HttpEvent</a>&lt;any&gt;</code> 的可观察对象。</p><p translation-origin="off">Instead they return observables of <code><a href="api/common/http/HttpEvent" class="code-anchor">HttpEvent</a>&lt;any&gt;</code>.</p><p translation-result="on">这是因为拦截器工作的层级比那些 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 方法更低一些。每个 HTTP 请求都可能会生成很多个<em>事件</em>，包括上传和下载的进度事件。 实际上，<code><a href="api/common/http/HttpResponse" class="code-anchor">HttpResponse</a></code> 类本身就是一个事件，它的类型（<code>type</code>）是 <code>HttpEventType.HttpResponseEvent</code>。</p><p translation-origin="off">That's because interceptors work at a lower level than those <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> methods. A single HTTP request can generate multiple <em>events</em>, including upload and download progress events. The <code><a href="api/common/http/HttpResponse" class="code-anchor">HttpResponse</a></code> class itself is actually an event, whose type is <code>HttpEventType.HttpResponseEvent</code>.</p><p translation-result="on">很多拦截器只关心发出的请求，而对 <code>next.handle()</code> 返回的事件流不会做任何修改。</p><p translation-origin="off">Many interceptors are only concerned with the outgoing request and simply return the event stream from <code>next.handle()</code> without modifying it.</p><p translation-result="on">但那些要检查和修改来自 <code>next.handle()</code> 的响应体的拦截器希望看到所有这些事件。 所以，你的拦截器应该返回<em>你没碰过的所有事件</em>，除非你<em>有充分的理由不这么做</em>。</p><p translation-origin="off">But interceptors that examine and modify the response from <code>next.handle()</code> will see all of these events. Your interceptor should return <em>every event untouched</em> unless it has a <em>compelling reason to do otherwise</em>.</p><h4 id="immutability" translation-result="on">不可变性<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#immutability"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="immutability">Immutability<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#immutability"><i class="material-icons">link</i></a></h4><p translation-result="on">虽然拦截器有能力改变请求和响应，但 <code><a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a></code> 和 <code><a href="api/common/http/HttpResponse" class="code-anchor">HttpResponse</a></code> 实例的属性却是只读（<code>readonly</code>）的， 因此让它们基本上是不可变的。</p><p translation-origin="off">Although interceptors are capable of mutating requests and responses, the <code><a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a></code> and <code><a href="api/common/http/HttpResponse" class="code-anchor">HttpResponse</a></code> instance properties are <code>readonly</code>, rendering them largely immutable.</p><p translation-result="on">有充足的理由把它们做成不可变对象：应用可能会重试发送很多次请求之后才能成功，这就意味着这个拦截器链表可能会多次重复处理同一个请求。 如果拦截器可以修改原始的请求对象，那么重试阶段的操作就会从修改过的请求开始，而不是原始请求。 而这种不可变性，可以确保这些拦截器在每次重试时看到的都是同样的原始请求。</p><p translation-origin="off">They are immutable for a good reason: the app may retry a request several times before it succeeds, which means that the interceptor chain may re-process the same request multiple times. If an interceptor could modify the original request object, the re-tried operation would start from the modified request rather than the original. Immutability ensures that interceptors see the same request for each try.</p><p translation-result="on">通过把 <code><a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a></code> 的属性设置为只读的，TypeScript 可以防止你犯这种错误。</p><p translation-origin="off">TypeScript will prevent you from setting <code><a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a></code> readonly properties.</p><code-example language="javascript" ng-version="7.0.0"><div style="display:none">// Typescript disallows the following assignment because req.url is readonly req.url = req.url.replace('<a href="api/common/http" class="code-anchor">http</a>://', 'https://');</div><aio-code><pre class="prettyprint lang-javascript">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// Typescript disallows the following assignment because req.url is readonly</span><span class="pln">
req</span><span class="pun">.</span><span class="pln">url </span><span class="pun">=</span><span class="pln"> req</span><span class="pun">.</span><span class="pln">url</span><span class="pun">.</span><span class="pln">replace</span><span class="pun">(</span><span class="str">'</span><a href="api/common/http" class="code-anchor"><span class="str">http</span></a><span class="str">://'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'https://'</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><p translation-result="on">要想修改该请求，就要先克隆它，并修改这个克隆体，然后再把这个克隆体传给 <code>next.handle()</code>。 你可以用一步操作中完成对请求的克隆和修改，例子如下：</p><p translation-origin="off">To alter the request, clone it first and modify the clone before passing it to <code>next.handle()</code>. You can clone and modify the request in a single step as in this example.</p><code-example path="http/src/app/http-interceptors/ensure-https-interceptor.ts" region="excerpt" header="app/http-interceptors/ensure-https-interceptor.ts (excerpt)" linenums="false" ng-version="7.0.0"><div style="display:none">// clone request and replace '<a href="api/common/http" class="code-anchor">http</a>://' with 'https://' at the same time const secureReq = req.clone({ url: req.url.replace('<a href="api/common/http" class="code-anchor">http</a>://', 'https://') }); // send the cloned, "secure" request to the next handler. return next.handle(secureReq);</div><header class="ng-star-inserted">app/http-interceptors/ensure-https-interceptor.ts (excerpt)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/http-interceptors/ensure-https-interceptor.ts (excerpt)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// clone request and replace '</span><a href="api/common/http" class="code-anchor"><span class="com">http</span></a><span class="com">://' with 'https://' at the same time</span><span class="pln">
</span><span class="kwd">const</span><span class="pln"> secureReq </span><span class="pun">=</span><span class="pln"> req</span><span class="pun">.</span><span class="pln">clone</span><span class="pun">({</span><span class="pln">
  url</span><span class="pun">:</span><span class="pln"> req</span><span class="pun">.</span><span class="pln">url</span><span class="pun">.</span><span class="pln">replace</span><span class="pun">(</span><span class="str">'</span><a href="api/common/http" class="code-anchor"><span class="str">http</span></a><span class="str">://'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'https://'</span><span class="pun">)</span><span class="pln">
</span><span class="pun">});</span><span class="pln">
</span><span class="com">// send the cloned, "secure" request to the next handler.</span><span class="pln">
</span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">.</span><span class="pln">handle</span><span class="pun">(</span><span class="pln">secureReq</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><p translation-result="on">这个 <code>clone()</code> 方法的哈希型参数允许你在复制出克隆体的同时改变该请求的某些特定属性。</p><p translation-origin="off">The <code>clone()</code> method's hash argument allows you to mutate specific properties of the request while copying the others.</p><h5 id="the-request-body" translation-result="on">请求体<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#the-request-body"><i class="material-icons">link</i></a></h5><h5 translation-origin="off" id="the-request-body">The request body<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#the-request-body"><i class="material-icons">link</i></a></h5><p translation-result="on"><code>readonly</code> 这种赋值保护，无法防范深修改（修改子对象的属性），也不能防范你修改请求体对象中的属性。</p><p translation-origin="off">The <code>readonly</code> assignment guard can't prevent deep updates and, in particular, it can't prevent you from modifying a property of a request body object.</p><code-example language="javascript" ng-version="7.0.0"><div style="display:none">req.body.name = req.body.name.trim(); // bad idea!</div><aio-code><pre class="prettyprint lang-javascript">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">req</span><span class="pun">.</span><span class="pln">body</span><span class="pun">.</span><span class="pln">name </span><span class="pun">=</span><span class="pln"> req</span><span class="pun">.</span><span class="pln">body</span><span class="pun">.</span><span class="pln">name</span><span class="pun">.</span><span class="pln">trim</span><span class="pun">();</span><span class="pln"> </span><span class="com">// bad idea!</span></code>
    </pre></aio-code></code-example><p translation-result="on">如果你必须修改请求体，那么就要先复制它，然后修改这个副本，<code>clone()</code> 这个请求，然后把这个请求体的副本作为新的请求体，例子如下：</p><p translation-origin="off">If you must mutate the request body, copy it first, change the copy, <code>clone()</code> the request, and set the clone's body with the new body, as in the following example.</p><code-example path="http/src/app/http-interceptors/trim-name-interceptor.ts" region="excerpt" header="app/http-interceptors/trim-name-interceptor.ts (excerpt)" linenums="false" ng-version="7.0.0"><div style="display:none">// copy the body and trim whitespace from the name property const newBody = { ...body, name: body.name.trim() }; // clone request and set its body const newReq = req.clone({ body: newBody }); // send the cloned request to the next handler. return next.handle(newReq);</div><header class="ng-star-inserted">app/http-interceptors/trim-name-interceptor.ts (excerpt)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/http-interceptors/trim-name-interceptor.ts (excerpt)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// copy the body and trim whitespace from the name property</span><span class="pln">
</span><span class="kwd">const</span><span class="pln"> newBody </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="pun">...</span><span class="pln">body</span><span class="pun">,</span><span class="pln"> name</span><span class="pun">:</span><span class="pln"> body</span><span class="pun">.</span><span class="pln">name</span><span class="pun">.</span><span class="pln">trim</span><span class="pun">()</span><span class="pln"> </span><span class="pun">};</span><span class="pln">
</span><span class="com">// clone request and set its body</span><span class="pln">
</span><span class="kwd">const</span><span class="pln"> newReq </span><span class="pun">=</span><span class="pln"> req</span><span class="pun">.</span><span class="pln">clone</span><span class="pun">({</span><span class="pln"> body</span><span class="pun">:</span><span class="pln"> newBody </span><span class="pun">});</span><span class="pln">
</span><span class="com">// send the cloned request to the next handler.</span><span class="pln">
</span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">.</span><span class="pln">handle</span><span class="pun">(</span><span class="pln">newReq</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><h5 id="clearing-the-request-body" translation-result="on">清空请求体<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#clearing-the-request-body"><i class="material-icons">link</i></a></h5><h5 translation-origin="off" id="clearing-the-request-body">Clearing the request body<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#clearing-the-request-body"><i class="material-icons">link</i></a></h5><p translation-result="on">有时你需要清空请求体，而不是替换它。 如果你把克隆后的请求体设置成 <code>undefined</code>，Angular 会认为你是想让这个请求体保持原样。 这显然不是你想要的。 但如果把克隆后的请求体设置成 <code>null</code>，那 Angular 就知道你是想清空这个请求体了。</p><p translation-origin="off">Sometimes you need to clear the request body rather than replace it. If you set the cloned request body to <code>undefined</code>, Angular assumes you intend to leave the body as is. That is not what you want. If you set the cloned request body to <code>null</code>, Angular knows you intend to clear the request body.</p><code-example language="javascript" ng-version="7.0.0"><div style="display:none">newReq = req.clone({ ... }); // body not mentioned =&gt; preserve original body newReq = req.clone({ body: undefined }); // preserve original body newReq = req.clone({ body: null }); // clear the body</div><aio-code><pre class="prettyprint lang-javascript">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">newReq </span><span class="pun">=</span><span class="pln"> req</span><span class="pun">.</span><span class="pln">clone</span><span class="pun">({</span><span class="pln"> </span><span class="pun">...</span><span class="pln"> </span><span class="pun">});</span><span class="pln"> </span><span class="com">// body not mentioned =&gt; preserve original body</span><span class="pln">
newReq </span><span class="pun">=</span><span class="pln"> req</span><span class="pun">.</span><span class="pln">clone</span><span class="pun">({</span><span class="pln"> body</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">undefined</span><span class="pln"> </span><span class="pun">});</span><span class="pln"> </span><span class="com">// preserve original body</span><span class="pln">
newReq </span><span class="pun">=</span><span class="pln"> req</span><span class="pun">.</span><span class="pln">clone</span><span class="pun">({</span><span class="pln"> body</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">null</span><span class="pln"> </span><span class="pun">});</span><span class="pln"> </span><span class="com">// clear the body</span></code>
    </pre></aio-code></code-example><h4 id="set-default-headers" translation-result="on">设置默认请求头<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#set-default-headers"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="set-default-headers">Set default headers<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#set-default-headers"><i class="material-icons">link</i></a></h4><p translation-result="on">应用通常会使用拦截器来设置外发请求的默认请求头。</p><p translation-origin="off">Apps often use an interceptor to set default headers on outgoing requests.</p><p translation-result="on">该范例应用具有一个 <code>AuthService</code>，它会生成一个认证令牌。 在这里，<code>AuthInterceptor</code> 会注入该服务以获取令牌，并对每一个外发的请求添加一个带有该令牌的认证头：</p><p translation-origin="off">The sample app has an <code>AuthService</code> that produces an authorization token. Here is its <code>AuthInterceptor</code> that injects that service to get the token and adds an authorization header with that token to every outgoing request:</p><code-example path="http/src/app/http-interceptors/auth-interceptor.ts" header="app/http-interceptors/auth-interceptor.ts" ng-version="7.0.0"><div style="display:none">import { AuthService } from '../auth.service'; @<a href="api/core/Injectable" class="code-anchor">Injectable</a>() export class AuthInterceptor implements <a href="api/common/http/HttpInterceptor" class="code-anchor">HttpInterceptor</a> { constructor(private auth: AuthService) {} intercept(req: <a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a>&lt;any&gt;, next: <a href="api/common/http/HttpHandler" class="code-anchor">HttpHandler</a>) { // <a href="api/http/RequestMethod#Get" class="code-anchor">Get</a> the auth token from the service. const authToken = this.auth.getAuthorizationToken(); // Clone the request and replace the original headers with // cloned headers, updated with the authorization. const authReq = req.clone({ headers: req.headers.set('Authorization', authToken) }); // send cloned request with header to the next handler. return next.handle(authReq); } }</div><header class="ng-star-inserted">app/http-interceptors/auth-interceptor.ts</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/http-interceptors/auth-interceptor.ts">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><ol class="linenums"><li class="L0"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">AuthService</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'../auth.service'</span><span class="pun">;</span></li><li class="L1"><span class="pln">&nbsp;</span></li><li class="L2"><span class="lit">@</span><a href="api/core/Injectable" class="code-anchor"><span class="lit">Injectable</span></a><span class="pun">()</span></li><li class="L3"><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">AuthInterceptor</span><span class="pln"> </span><span class="kwd">implements</span><span class="pln"> </span><a href="api/common/http/HttpInterceptor" class="code-anchor"><span class="typ">HttpInterceptor</span></a><span class="pln"> </span><span class="pun">{</span></li><li class="L4"><span class="pln">&nbsp;</span></li><li class="L5"><span class="pln">  </span><span class="kwd">constructor</span><span class="pun">(</span><span class="kwd">private</span><span class="pln"> auth</span><span class="pun">:</span><span class="pln"> </span><span class="typ">AuthService</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{}</span></li><li class="L6"><span class="pln">&nbsp;</span></li><li class="L7"><span class="pln">  intercept</span><span class="pun">(</span><span class="pln">req</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpRequest" class="code-anchor"><span class="typ">HttpRequest</span></a><span class="str">&lt;any&gt;</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpHandler" class="code-anchor"><span class="typ">HttpHandler</span></a><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span></li><li class="L8"><span class="pln">    </span><span class="com">// </span><a href="api/http/RequestMethod#Get" class="code-anchor"><span class="com">Get</span></a><span class="com"> the auth token from the service.</span></li><li class="L9"><span class="pln">    </span><span class="kwd">const</span><span class="pln"> authToken </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">auth</span><span class="pun">.</span><span class="pln">getAuthorizationToken</span><span class="pun">();</span></li><li class="L0"><span class="pln">&nbsp;</span></li><li class="L1"><span class="pln">    </span><span class="com">// Clone the request and replace the original headers with</span></li><li class="L2"><span class="pln">    </span><span class="com">// cloned headers, updated with the authorization.</span></li><li class="L3"><span class="pln">    </span><span class="kwd">const</span><span class="pln"> authReq </span><span class="pun">=</span><span class="pln"> req</span><span class="pun">.</span><span class="pln">clone</span><span class="pun">({</span></li><li class="L4"><span class="pln">      headers</span><span class="pun">:</span><span class="pln"> req</span><span class="pun">.</span><span class="pln">headers</span><span class="pun">.</span><span class="kwd">set</span><span class="pun">(</span><span class="str">'Authorization'</span><span class="pun">,</span><span class="pln"> authToken</span><span class="pun">)</span></li><li class="L5"><span class="pln">    </span><span class="pun">});</span></li><li class="L6"><span class="pln">&nbsp;</span></li><li class="L7"><span class="pln">    </span><span class="com">// send cloned request with header to the next handler.</span></li><li class="L8"><span class="pln">    </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">.</span><span class="pln">handle</span><span class="pun">(</span><span class="pln">authReq</span><span class="pun">);</span></li><li class="L9"><span class="pln">  </span><span class="pun">}</span></li><li class="L0"><span class="pun">}</span></li></ol></code>
    </pre></aio-code></code-example><p translation-result="on">这种在克隆请求的同时设置新请求头的操作太常见了，因此它还有一个快捷方式 <code>setHeaders</code>：</p><p translation-origin="off">The practice of cloning a request to set new headers is so common that there's a <code>setHeaders</code> shortcut for it:</p><code-example path="http/src/app/http-interceptors/auth-interceptor.ts" region="set-header-shortcut" ng-version="7.0.0"><div style="display:none">// Clone the request and set the new header in one step. const authReq = req.clone({ setHeaders: { Authorization: authToken } });</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// Clone the request and set the new header in one step.</span><span class="pln">
</span><span class="kwd">const</span><span class="pln"> authReq </span><span class="pun">=</span><span class="pln"> req</span><span class="pun">.</span><span class="pln">clone</span><span class="pun">({</span><span class="pln"> setHeaders</span><span class="pun">:</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">Authorization</span><span class="pun">:</span><span class="pln"> authToken </span><span class="pun">}</span><span class="pln"> </span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">这种可以修改头的拦截器可以用于很多不同的操作，比如：</p><p translation-origin="off">An interceptor that alters headers can be used for a number of different operations, including:</p><ul><li><p translation-result="on">认证 / 授权</p><p translation-origin="off">Authentication/authorization</p></li><li><p translation-result="on">控制缓存行为。比如 <code>If-Modified-Since</code></p><p translation-origin="off">Caching behavior; for example, <code>If-Modified-Since</code></p></li><li><p translation-result="on">XSRF 防护</p><p translation-origin="off">XSRF protection</p></li></ul><h4 id="logging" translation-result="on">记日志<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#logging"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="logging">Logging<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#logging"><i class="material-icons">link</i></a></h4><p translation-result="on">因为拦截器可以<em>同时</em>处理请求和响应，所以它们也可以对整个 HTTP 操作进行计时和记录日志。</p><p translation-origin="off">Because interceptors can process the request and response <em>together</em>, they can do things like time and log an entire HTTP operation.</p><p translation-result="on">考虑下面这个 <code>LoggingInterceptor</code>，它捕获请求的发起时间、响应的接收时间，并使用注入的 <code>MessageService</code> 来发送总共花费的时间。</p><p translation-origin="off">Consider the following <code>LoggingInterceptor</code>, which captures the time of the request, the time of the response, and logs the outcome with the elapsed time with the injected <code>MessageService</code>.</p><code-example path="http/src/app/http-interceptors/logging-interceptor.ts" region="excerpt" header="app/http-interceptors/logging-interceptor.ts)" ng-version="7.0.0"><div style="display:none">import { finalize, tap } from 'rxjs/operators'; import { MessageService } from '../message.service'; @<a href="api/core/Injectable" class="code-anchor">Injectable</a>() export class LoggingInterceptor implements <a href="api/common/http/HttpInterceptor" class="code-anchor">HttpInterceptor</a> { constructor(private messenger: MessageService) {} intercept(req: <a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a>&lt;any&gt;, next: <a href="api/common/http/HttpHandler" class="code-anchor">HttpHandler</a>) { const started = Date.now(); let ok: string; // extend server response observable with logging return next.handle(req) .pipe( tap( // Succeeds when there is <a href="api/router/RouterLinkWithHref" class="code-anchor">a</a> response; ignore other events event =&gt; ok = event instanceof <a href="api/common/http/HttpResponse" class="code-anchor">HttpResponse</a> ? 'succeeded' : '', // Operation failed; error is an <a href="api/common/http/HttpErrorResponse" class="code-anchor">HttpErrorResponse</a> error =&gt; ok = 'failed' ), // Log when response observable either completes or errors finalize(() =&gt; { const elapsed = Date.now() - started; const msg = `${req.method} "${req.urlWithParams}" ${ok} in ${elapsed} ms.`; this.messenger.add(msg); }) ); } }</div><header class="ng-star-inserted">app/http-interceptors/logging-interceptor.ts)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/http-interceptors/logging-interceptor.ts)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><ol class="linenums"><li class="L0"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> finalize</span><span class="pun">,</span><span class="pln"> tap </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'rxjs/operators'</span><span class="pun">;</span></li><li class="L1"><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">MessageService</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'../message.service'</span><span class="pun">;</span></li><li class="L2"><span class="pln">&nbsp;</span></li><li class="L3"><span class="lit">@</span><a href="api/core/Injectable" class="code-anchor"><span class="lit">Injectable</span></a><span class="pun">()</span></li><li class="L4"><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">LoggingInterceptor</span><span class="pln"> </span><span class="kwd">implements</span><span class="pln"> </span><a href="api/common/http/HttpInterceptor" class="code-anchor"><span class="typ">HttpInterceptor</span></a><span class="pln"> </span><span class="pun">{</span></li><li class="L5"><span class="pln">  </span><span class="kwd">constructor</span><span class="pun">(</span><span class="kwd">private</span><span class="pln"> messenger</span><span class="pun">:</span><span class="pln"> </span><span class="typ">MessageService</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{}</span></li><li class="L6"><span class="pln">&nbsp;</span></li><li class="L7"><span class="pln">  intercept</span><span class="pun">(</span><span class="pln">req</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpRequest" class="code-anchor"><span class="typ">HttpRequest</span></a><span class="str">&lt;any&gt;</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpHandler" class="code-anchor"><span class="typ">HttpHandler</span></a><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span></li><li class="L8"><span class="pln">    </span><span class="kwd">const</span><span class="pln"> started </span><span class="pun">=</span><span class="pln"> </span><span class="typ">Date</span><span class="pun">.</span><span class="pln">now</span><span class="pun">();</span></li><li class="L9"><span class="pln">    </span><span class="kwd">let</span><span class="pln"> ok</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">string</span><span class="pun">;</span></li><li class="L0"><span class="pln">&nbsp;</span></li><li class="L1"><span class="pln">    </span><span class="com">// extend server response observable with logging</span></li><li class="L2"><span class="pln">    </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">.</span><span class="pln">handle</span><span class="pun">(</span><span class="pln">req</span><span class="pun">)</span></li><li class="L3"><span class="pln">      </span><span class="pun">.</span><span class="pln">pipe</span><span class="pun">(</span></li><li class="L4"><span class="pln">        tap</span><span class="pun">(</span></li><li class="L5"><span class="pln">          </span><span class="com">// Succeeds when there is </span><a href="api/router/RouterLinkWithHref" class="code-anchor"><span class="com">a</span></a><span class="com"> response; ignore other events</span></li><li class="L6"><span class="pln">          </span><span class="kwd">event</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> ok </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">event</span><span class="pln"> </span><span class="kwd">instanceof</span><span class="pln"> </span><a href="api/common/http/HttpResponse" class="code-anchor"><span class="typ">HttpResponse</span></a><span class="pln"> </span><span class="pun">?</span><span class="pln"> </span><span class="str">'succeeded'</span><span class="pln"> </span><span class="pun">:</span><span class="pln"> </span><span class="str">''</span><span class="pun">,</span></li><li class="L7"><span class="pln">          </span><span class="com">// Operation failed; error is an </span><a href="api/common/http/HttpErrorResponse" class="code-anchor"><span class="com">HttpErrorResponse</span></a></li><li class="L8"><span class="pln">          error </span><span class="pun">=&gt;</span><span class="pln"> ok </span><span class="pun">=</span><span class="pln"> </span><span class="str">'failed'</span></li><li class="L9"><span class="pln">        </span><span class="pun">),</span></li><li class="L0"><span class="pln">        </span><span class="com">// Log when response observable either completes or errors</span></li><li class="L1"><span class="pln">        finalize</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span></li><li class="L2"><span class="pln">          </span><span class="kwd">const</span><span class="pln"> elapsed </span><span class="pun">=</span><span class="pln"> </span><span class="typ">Date</span><span class="pun">.</span><span class="pln">now</span><span class="pun">()</span><span class="pln"> </span><span class="pun">-</span><span class="pln"> started</span><span class="pun">;</span></li><li class="L3"><span class="pln">          </span><span class="kwd">const</span><span class="pln"> msg </span><span class="pun">=</span><span class="pln"> </span><span class="str">`${req.method} "${req.urlWithParams}"</span></li><li class="L4"><span class="str">             ${ok} in ${elapsed} ms.`</span><span class="pun">;</span></li><li class="L5"><span class="pln">          </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">messenger</span><span class="pun">.</span><span class="kwd">add</span><span class="pun">(</span><span class="pln">msg</span><span class="pun">);</span></li><li class="L6"><span class="pln">        </span><span class="pun">})</span></li><li class="L7"><span class="pln">      </span><span class="pun">);</span></li><li class="L8"><span class="pln">  </span><span class="pun">}</span></li><li class="L9"><span class="pun">}</span></li></ol></code>
    </pre></aio-code></code-example><p translation-result="on">RxJS 的 <code>tap</code> 操作符会捕获请求成功了还是失败了。 RxJS 的 <code>finalize</code> 操作符无论在响应成功还是失败时都会调用（这是必须的），然后把结果汇报给 <code>MessageService</code>。</p><p translation-origin="off">The RxJS <code>tap</code> operator captures whether the request succeed or failed. The RxJS <code>finalize</code> operator is called when the response observable either errors or completes (which it must), and reports the outcome to the <code>MessageService</code>.</p><p translation-result="on">在这个可观察对象的流中，无论是 <code>tap</code> 还是 <code>finalize</code> 接触过的值，都会照常发送给调用者。</p><p translation-origin="off">Neither <code>tap</code> nor <code>finalize</code> touch the values of the observable stream returned to the caller.</p><h4 id="caching" translation-result="on">缓存<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#caching"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="caching">Caching<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#caching"><i class="material-icons">link</i></a></h4><p translation-result="on">拦截器还可以自行处理这些请求，而不用转发给 <code>next.handle()</code>。</p><p translation-origin="off">Interceptors can handle requests by themselves, without forwarding to <code>next.handle()</code>.</p><p translation-result="on">比如，你可能会想缓存某些请求和响应，以便提升性能。 你可以把这种缓存操作委托给某个拦截器，而不破坏你现有的各个数据服务。</p><p translation-origin="off">For example, you might decide to cache certain requests and responses to improve performance. You can delegate caching to an interceptor without disturbing your existing data services.</p><p translation-result="on"><code>CachingInterceptor</code> 演示了这种方式。</p><p translation-origin="off">The <code>CachingInterceptor</code> demonstrates this approach.</p><code-example path="http/src/app/http-interceptors/caching-interceptor.ts" region="v1" header="app/http-interceptors/caching-interceptor.ts)" linenums="false" ng-version="7.0.0"><div style="display:none">@<a href="api/core/Injectable" class="code-anchor">Injectable</a>() export class CachingInterceptor implements <a href="api/common/http/HttpInterceptor" class="code-anchor">HttpInterceptor</a> { constructor(private cache: RequestCache) {} intercept(req: <a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a>&lt;any&gt;, next: <a href="api/common/http/HttpHandler" class="code-anchor">HttpHandler</a>) { // continue if not cachable. if (!isCachable(req)) { return next.handle(req); } const cachedResponse = this.cache.get(req); return cachedResponse ? of(cachedResponse) : sendRequest(req, next, this.cache); } }</div><header class="ng-star-inserted">app/http-interceptors/caching-interceptor.ts)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/http-interceptors/caching-interceptor.ts)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="lit">@</span><a href="api/core/Injectable" class="code-anchor"><span class="lit">Injectable</span></a><span class="pun">()</span><span class="pln">
</span><span class="kwd">export</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">CachingInterceptor</span><span class="pln"> </span><span class="kwd">implements</span><span class="pln"> </span><a href="api/common/http/HttpInterceptor" class="code-anchor"><span class="typ">HttpInterceptor</span></a><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">constructor</span><span class="pun">(</span><span class="kwd">private</span><span class="pln"> cache</span><span class="pun">:</span><span class="pln"> </span><span class="typ">RequestCache</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{}</span><span class="pln">

  intercept</span><span class="pun">(</span><span class="pln">req</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpRequest" class="code-anchor"><span class="typ">HttpRequest</span></a><span class="str">&lt;any&gt;</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpHandler" class="code-anchor"><span class="typ">HttpHandler</span></a><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="com">// continue if not cachable.</span><span class="pln">
    </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(!</span><span class="pln">isCachable</span><span class="pun">(</span><span class="pln">req</span><span class="pun">))</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">.</span><span class="pln">handle</span><span class="pun">(</span><span class="pln">req</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln">

    </span><span class="kwd">const</span><span class="pln"> cachedResponse </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">cache</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">(</span><span class="pln">req</span><span class="pun">);</span><span class="pln">
    </span><span class="kwd">return</span><span class="pln"> cachedResponse </span><span class="pun">?</span><span class="pln">
      of</span><span class="pun">(</span><span class="pln">cachedResponse</span><span class="pun">)</span><span class="pln"> </span><span class="pun">:</span><span class="pln"> sendRequest</span><span class="pun">(</span><span class="pln">req</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">cache</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>isCachable()</code> 函数用于决定该请求是否允许缓存。 在这个例子中，只有发到 npm 包搜索 API 的 GET 请求才是可以缓存的。</p><p translation-origin="off">The <code>isCachable()</code> function determines if the request is cachable. In this sample, only GET requests to the npm package search api are cachable.</p><p translation-result="on">如果该请求是不可缓存的，该拦截器只会把该请求转发给链表中的下一个处理器。</p><p translation-origin="off">If the request is not cachable, the interceptor simply forwards the request to the next handler in the chain.</p><p translation-result="on">如果可缓存的请求在缓存中找到了，该拦截器就会通过 <code>of()</code> 函数返回一个已缓存的响应体的<em>可观察对象</em>，然后把它传给 <code>next</code> 处理器（以及所有其它下游拦截器）。</p><p translation-origin="off">If a cachable request is found in the cache, the interceptor returns an <code>of()</code> <em>observable</em> with the cached response, by-passing the <code>next</code> handler (and all other interceptors downstream).</p><p translation-result="on">如果可缓存的请求在缓存中没找到，代码就会调用 <code>sendRequest</code>。</p><p translation-origin="off">If a cachable request is not in cache, the code calls <code>sendRequest</code>.</p><a id="send-request"></a><code-example path="http/src/app/http-interceptors/caching-interceptor.ts" region="send-request" ng-version="7.0.0"><div style="display:none">/** * <a href="api/http/RequestMethod#Get" class="code-anchor">Get</a> server response observable by sending request to `next()`. * Will add the response to the cache on the way out. */ function sendRequest( req: <a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a>&lt;any&gt;, next: <a href="api/common/http/HttpHandler" class="code-anchor">HttpHandler</a>, cache: RequestCache): Observable&lt;<a href="api/common/http/HttpEvent" class="code-anchor">HttpEvent</a>&lt;any&gt;&gt; { // No headers allowed in npm <a href="api/common/PlatformLocation#search" class="code-anchor">search</a> request const noHeaderReq = req.clone({ headers: new <a href="api/common/http/HttpHeaders" class="code-anchor">HttpHeaders</a>() }); return next.handle(noHeaderReq).pipe( tap(event =&gt; { // There may be other events besides the response. if (event instanceof <a href="api/common/http/HttpResponse" class="code-anchor">HttpResponse</a>) { cache.put(req, event); // Update the cache. } }) ); }</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><ol class="linenums"><li class="L0"><span class="com">/**</span></li><li class="L1"><span class="com"> * </span><a href="api/http/RequestMethod#Get" class="code-anchor"><span class="com">Get</span></a><span class="com"> server response observable by sending request to `next()`.</span></li><li class="L2"><span class="com"> * Will add the response to the cache on the way out.</span></li><li class="L3"><span class="com"> */</span></li><li class="L4"><span class="kwd">function</span><span class="pln"> sendRequest</span><span class="pun">(</span></li><li class="L5"><span class="pln">  req</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpRequest" class="code-anchor"><span class="typ">HttpRequest</span></a><span class="str">&lt;any&gt;</span><span class="pun">,</span></li><li class="L6"><span class="pln">  </span><span class="kwd">next</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpHandler" class="code-anchor"><span class="typ">HttpHandler</span></a><span class="pun">,</span></li><li class="L7"><span class="pln">  cache</span><span class="pun">:</span><span class="pln"> </span><span class="typ">RequestCache</span><span class="pun">):</span><span class="pln"> </span><span class="typ">Observable</span><span class="pun">&lt;</span><a href="api/common/http/HttpEvent" class="code-anchor"><span class="typ">HttpEvent</span></a><span class="str">&lt;any&gt;</span><span class="pun">&gt;</span><span class="pln"> </span><span class="pun">{</span></li><li class="L8"><span class="pln">&nbsp;</span></li><li class="L9"><span class="pln">  </span><span class="com">// No headers allowed in npm </span><a href="api/common/PlatformLocation#search" class="code-anchor"><span class="com">search</span></a><span class="com"> request</span></li><li class="L0"><span class="pln">  </span><span class="kwd">const</span><span class="pln"> noHeaderReq </span><span class="pun">=</span><span class="pln"> req</span><span class="pun">.</span><span class="pln">clone</span><span class="pun">({</span><span class="pln"> headers</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><a href="api/common/http/HttpHeaders" class="code-anchor"><span class="typ">HttpHeaders</span></a><span class="pun">()</span><span class="pln"> </span><span class="pun">});</span></li><li class="L1"><span class="pln">&nbsp;</span></li><li class="L2"><span class="pln">  </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">.</span><span class="pln">handle</span><span class="pun">(</span><span class="pln">noHeaderReq</span><span class="pun">).</span><span class="pln">pipe</span><span class="pun">(</span></li><li class="L3"><span class="pln">    tap</span><span class="pun">(</span><span class="kwd">event</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span></li><li class="L4"><span class="pln">      </span><span class="com">// There may be other events besides the response.</span></li><li class="L5"><span class="pln">      </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="kwd">event</span><span class="pln"> </span><span class="kwd">instanceof</span><span class="pln"> </span><a href="api/common/http/HttpResponse" class="code-anchor"><span class="typ">HttpResponse</span></a><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span></li><li class="L6"><span class="pln">        cache</span><span class="pun">.</span><span class="pln">put</span><span class="pun">(</span><span class="pln">req</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">event</span><span class="pun">);</span><span class="pln"> </span><span class="com">// Update the cache.</span></li><li class="L7"><span class="pln">      </span><span class="pun">}</span></li><li class="L8"><span class="pln">    </span><span class="pun">})</span></li><li class="L9"><span class="pln">  </span><span class="pun">);</span></li><li class="L0"><span class="pun">}</span></li></ol></code>
    </pre></aio-code></code-example><p translation-result="on"><code>sendRequest</code> 函数创建了一个不带请求头的<a href="guide/http#immutability">请求克隆体</a>，因为 npm API 不会接受它们。</p><p translation-origin="off">The <code>sendRequest</code> function creates a <a href="guide/http#immutability">request clone</a> without headers because the npm api forbids them.</p><p translation-result="on">它会把这个请求转发给 <code>next.handle()</code>，它最终会调用服务器，并且返回服务器的响应。</p><p translation-origin="off">It forwards that request to <code>next.handle()</code> which ultimately calls the server and returns the server's response.</p><p translation-result="on">注意 <code>sendRequest</code> 是如何在发回给应用之前<em>拦截这个响应的</em>。 它会通过 <code>tap()</code> 操作符对响应进行管道处理，并在其回调中把响应加到缓存中。</p><p translation-origin="off">Note how <code>sendRequest</code> <em>intercepts the response</em> on its way back to the application. It <em>pipes</em> the response through the <code>tap()</code> operator, whose callback adds the response to the cache.</p><p translation-result="on">然后，原始的响应会通过这些拦截器链，原封不动的回到服务器的调用者那里。</p><p translation-origin="off">The original response continues untouched back up through the chain of interceptors to the application caller.</p><p translation-result="on">数据服务，比如 <code>PackageSearchService</code>，并不知道它们收到的某些 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 请求实际上是从缓存的请求中返回来的。</p><p translation-origin="off">Data services, such as <code>PackageSearchService</code>, are unaware that some of their <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> requests actually return cached responses.</p><a id="cache-refresh"></a><h4 id="return-a-multi-valued-observable" translation-result="on">返回多值可观察对象<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#return-a-multi-valued-observable"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="return-a-multi-valued-observable">Return a multi-valued <em>Observable</em><a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#return-a-multi-valued-observable"><i class="material-icons">link</i></a></h4><p translation-result="on"><code><a href="api/common/http/HttpClient#get" class="code-anchor">HttpClient.get()</a></code> 方法正常情况下只会返回一个<em>可观察对象</em>，它或者发出数据，或者发出错误。 有些人说它是“一次性完成”的可观察对象。</p><p translation-origin="off">The <code><a href="api/common/http/HttpClient#get" class="code-anchor">HttpClient.get()</a></code> method normally returns an <em>observable</em> that either emits the data or an error. Some folks describe it as a "<em>one and done</em>" observable.</p><p translation-result="on">但是拦截器也可以把这个修改成发出多个值的<em>可观察对象</em>。</p><p translation-origin="off">But an interceptor can change this to an <em>observable</em> that emits more than once.</p><p translation-result="on">修改后的 <code>CachingInterceptor</code> 版本可以返回一个立即发出缓存的响应，然后仍然把请求发送到 NPM 的 Web API，然后再把修改过的搜索结果重新发出一次。</p><p translation-origin="off">A revised version of the <code>CachingInterceptor</code> optionally returns an <em>observable</em> that immediately emits the cached response, sends the request to the NPM web API anyway, and emits again later with the updated search results.</p><code-example path="http/src/app/http-interceptors/caching-interceptor.ts" region="intercept-refresh" ng-version="7.0.0"><div style="display:none">// cache-then-refresh if (req.headers.get('x-refresh')) { const results$ = sendRequest(req, next, this.cache); return cachedResponse ? results$.pipe( startWith(cachedResponse) ) : results$; } // cache-or-fetch return cachedResponse ? of(cachedResponse) : sendRequest(req, next, this.cache);</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// cache-then-refresh</span><span class="pln">
</span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="pln">req</span><span class="pun">.</span><span class="pln">headers</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">(</span><span class="str">'x-refresh'</span><span class="pun">))</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> results$ </span><span class="pun">=</span><span class="pln"> sendRequest</span><span class="pun">(</span><span class="pln">req</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">cache</span><span class="pun">);</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> cachedResponse </span><span class="pun">?</span><span class="pln">
    results$</span><span class="pun">.</span><span class="pln">pipe</span><span class="pun">(</span><span class="pln"> startWith</span><span class="pun">(</span><span class="pln">cachedResponse</span><span class="pun">)</span><span class="pln"> </span><span class="pun">)</span><span class="pln"> </span><span class="pun">:</span><span class="pln">
    results$</span><span class="pun">;</span><span class="pln">
</span><span class="pun">}</span><span class="pln">
</span><span class="com">// cache-or-fetch</span><span class="pln">
</span><span class="kwd">return</span><span class="pln"> cachedResponse </span><span class="pun">?</span><span class="pln">
  of</span><span class="pun">(</span><span class="pln">cachedResponse</span><span class="pun">)</span><span class="pln"> </span><span class="pun">:</span><span class="pln"> sendRequest</span><span class="pun">(</span><span class="pln">req</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">next</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">cache</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><p translation-result="on">这种<em>缓存并刷新</em>的选项是由<strong>自定义的 <code>x-refresh</code> 头</strong>触发的。</p><p translation-origin="off">The <em>cache-then-refresh</em> option is triggered by the presence of a <strong>custom <code>x-refresh</code> header</strong>.</p><div class="alert is-helpful"><p translation-result="on"><code>PackageSearchComponent</code> 中的一个检查框会切换 <code>withRefresh</code> 标识， 它是 <code>PackageSearchService.search()</code> 的参数之一。 <code><a href="api/common/PlatformLocation#search" class="code-anchor">search</a>()</code> 方法创建了自定义的 <code>x-refresh</code> 头，并在调用 <code><a href="api/common/http/HttpClient#get" class="code-anchor">HttpClient.get()</a></code> 前把它添加到请求里。</p><p translation-origin="off">A checkbox on the <code>PackageSearchComponent</code> toggles a <code>withRefresh</code> flag, which is one of the arguments to <code>PackageSearchService.search()</code>. That <code><a href="api/common/PlatformLocation#search" class="code-anchor">search</a>()</code> method creates the custom <code>x-refresh</code> header and adds it to the request before calling <code><a href="api/common/http/HttpClient#get" class="code-anchor">HttpClient.get()</a></code>.</p></div><p translation-result="on">修改后的 <code>CachingInterceptor</code> 会发起一个服务器请求，而不管有没有缓存的值。 就像 <a href="guide/http#send-request">前面</a> 的 <code>sendRequest()</code> 方法一样进行订阅。 在订阅 <code>results$</code> 可观察对象时，就会发起这个请求。</p><p translation-origin="off">The revised <code>CachingInterceptor</code> sets up a server request whether there's a cached value or not, using the same <code>sendRequest()</code> method described <a href="guide/http#send-request">above</a>. The <code>results$</code> observable will make the request when subscribed.</p><p translation-result="on">如果没有缓存的值，拦截器直接返回 <code>result$</code>。</p><p translation-origin="off">If there's no cached value, the interceptor returns <code>results$</code>.</p><p translation-result="on">如果有缓存的值，这些代码就会把缓存的响应加入到 <code>result$</code> 的管道中，使用重组后的可观察对象进行处理，并发出两次。 先立即发出一次缓存的响应体，然后发出来自服务器的响应。 订阅者将会看到一个包含这<em>两个</em>响应的序列。</p><p translation-origin="off">If there is a cached value, the code <em>pipes</em> the cached response onto <code>results$</code>, producing a recomposed observable that emits twice, the cached response first (and immediately), followed later by the response from the server. Subscribers see a sequence of <em>two</em> responses.</p><h3 id="listening-to-progress-events" translation-result="on">监听进度事件<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#listening-to-progress-events"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="listening-to-progress-events">Listening to progress events<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#listening-to-progress-events"><i class="material-icons">link</i></a></h3><p translation-result="on">有时，应用会传输大量数据，并且这些传输可能会花费很长时间。 典型的例子是文件上传。 可以通过在传输过程中提供进度反馈，来提升用户体验。</p><p translation-origin="off">Sometimes applications transfer large amounts of data and those transfers can take a long time. File uploads are a typical example. Give the users a better experience by providing feedback on the progress of such transfers.</p><p translation-result="on">要想发起带有进度事件的请求，你可以创建一个把 <code><a href="api/common/http/HttpRequest#reportProgress" class="code-anchor">reportProgress</a></code> 选项设置为 <code>true</code> 的 <code><a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a></code> 实例，以开启进度跟踪事件。</p><p translation-origin="off">To make a request with progress events enabled, you can create an instance of <code><a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a></code> with the <code><a href="api/common/http/HttpRequest#reportProgress" class="code-anchor">reportProgress</a></code> option set true to enable tracking of progress events.</p><code-example path="http/src/app/uploader/uploader.service.ts" region="upload-request" header="app/uploader/uploader.service.ts (upload request)" ng-version="7.0.0"><div style="display:none">const req = new <a href="api/common/http/HttpRequest" class="code-anchor">HttpRequest</a>('POST', '/upload/file', file, { <a href="api/common/http/HttpRequest#reportProgress" class="code-anchor">reportProgress</a>: true });</div><header class="ng-star-inserted">app/uploader/uploader.service.ts (upload request)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/uploader/uploader.service.ts (upload request)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="kwd">const</span><span class="pln"> req </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><a href="api/common/http/HttpRequest" class="code-anchor"><span class="typ">HttpRequest</span></a><span class="pun">(</span><span class="str">'POST'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'/upload/file'</span><span class="pun">,</span><span class="pln"> file</span><span class="pun">,</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><a href="api/common/http/HttpRequest#reportProgress" class="code-anchor"><span class="pln">reportProgress</span></a><span class="pun">:</span><span class="pln"> </span><span class="kwd">true</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><div class="alert is-important"><p translation-result="on">每个进度事件都会触发变更检测，所以，你应该只有当确实希望在 UI 中报告进度时才打开这个选项。</p><p translation-origin="off">Every progress event triggers change detection, so only turn them on if you truly intend to report progress in the UI.</p></div><p translation-result="on">接下来，把这个请求对象传给 <code><a href="api/common/http/HttpClient#request" class="code-anchor">HttpClient.request()</a></code> 方法，它返回一个 <code>HttpEvents</code> 的 <code>Observable</code>，同样也可以在拦截器中处理这些事件。</p><p translation-origin="off">Next, pass this request object to the <code><a href="api/common/http/HttpClient#request" class="code-anchor">HttpClient.request()</a></code> method, which returns an <code>Observable</code> of <code>HttpEvents</code>, the same events processed by interceptors:</p><code-example path="http/src/app/uploader/uploader.service.ts" region="upload-body" header="app/uploader/uploader.service.ts (upload body)" linenums="false" ng-version="7.0.0"><div style="display:none">// The `HttpClient.request` API produces <a href="api/router/RouterLinkWithHref" class="code-anchor">a</a> raw event stream // which includes start (sent), progress, and response events. return this.http.request(req).pipe( map(event =&gt; this.getEventMessage(event, file)), tap(<a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a> =&gt; this.showProgress(<a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a>)), last(), // return last (completed) <a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a> to caller catchError(this.handleError(file)) );</div><header class="ng-star-inserted">app/uploader/uploader.service.ts (upload body)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/uploader/uploader.service.ts (upload body)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// The `HttpClient.request` API produces </span><a href="api/router/RouterLinkWithHref" class="code-anchor"><span class="com">a</span></a><span class="com"> raw event stream</span><span class="pln">
</span><span class="com">// which includes start (sent), progress, and response events.</span><span class="pln">
</span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">http</span><span class="pun">.</span><span class="pln">request</span><span class="pun">(</span><span class="pln">req</span><span class="pun">).</span><span class="pln">pipe</span><span class="pun">(</span><span class="pln">
  map</span><span class="pun">(</span><span class="kwd">event</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">getEventMessage</span><span class="pun">(</span><span class="kwd">event</span><span class="pun">,</span><span class="pln"> file</span><span class="pun">)),</span><span class="pln">
  tap</span><span class="pun">(</span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="pln">message</span></a><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">showProgress</span><span class="pun">(</span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="pln">message</span></a><span class="pun">)),</span><span class="pln">
  </span><span class="kwd">last</span><span class="pun">(),</span><span class="pln"> </span><span class="com">// return last (completed) </span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="com">message</span></a><span class="com"> to caller</span><span class="pln">
  catchError</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">handleError</span><span class="pun">(</span><span class="pln">file</span><span class="pun">))</span><span class="pln">
</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><p translation-result="on"><code>getEventMessage</code> 方法会解释事件流中的每一个 <code><a href="api/common/http/HttpEvent" class="code-anchor">HttpEvent</a></code> 类型。</p><p translation-origin="off">The <code>getEventMessage</code> method interprets each type of <code><a href="api/common/http/HttpEvent" class="code-anchor">HttpEvent</a></code> in the event stream.</p><code-example path="http/src/app/uploader/uploader.service.ts" region="getEventMessage" header="app/uploader/uploader.service.ts (getEventMessage)" linenums="false" ng-version="7.0.0"><div style="display:none">/** Return distinct <a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a> for sent, upload progress, &amp; response events */ private getEventMessage(event: <a href="api/common/http/HttpEvent" class="code-anchor">HttpEvent</a>&lt;any&gt;, file: File) { switch (event.type) { case <a href="api/common/http/HttpEventType#Sent" class="code-anchor">HttpEventType.Sent</a>: return `Uploading file "${file.name}" of size ${file.size}.`; case <a href="api/common/http/HttpEventType#UploadProgress" class="code-anchor">HttpEventType.UploadProgress</a>: // Compute and show the % <a href="api/core/ApplicationInitStatus#done" class="code-anchor">done</a>: const percentDone = Math.round(100 * event.loaded / event.total); return `File "${file.name}" is ${percentDone}% uploaded.`; case <a href="api/common/http/HttpEventType#Response" class="code-anchor">HttpEventType.Response</a>: return `File "${file.name}" was completely uploaded!`; default: return `File "${file.name}" surprising upload event: ${event.type}.`; } }</div><header class="ng-star-inserted">app/uploader/uploader.service.ts (getEventMessage)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/uploader/uploader.service.ts (getEventMessage)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">/** Return distinct </span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="com">message</span></a><span class="com"> for sent, upload progress, &amp; response events */</span><span class="pln">
</span><span class="kwd">private</span><span class="pln"> getEventMessage</span><span class="pun">(</span><span class="kwd">event</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpEvent" class="code-anchor"><span class="typ">HttpEvent</span></a><span class="str">&lt;any&gt;</span><span class="pun">,</span><span class="pln"> file</span><span class="pun">:</span><span class="pln"> </span><span class="typ">File</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">switch</span><span class="pln"> </span><span class="pun">(</span><span class="kwd">event</span><span class="pun">.</span><span class="pln">type</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">case</span><span class="pln"> </span><a href="api/common/http/HttpEventType#Sent" class="code-anchor"><span class="typ">HttpEventType</span><span class="pun">.</span><span class="typ">Sent</span></a><span class="pun">:</span><span class="pln">
      </span><span class="kwd">return</span><span class="pln"> </span><span class="str">`Uploading file "${file.name}" of size ${file.size}.`</span><span class="pun">;</span><span class="pln">

    </span><span class="kwd">case</span><span class="pln"> </span><a href="api/common/http/HttpEventType#UploadProgress" class="code-anchor"><span class="typ">HttpEventType</span><span class="pun">.</span><span class="typ">UploadProgress</span></a><span class="pun">:</span><span class="pln">
      </span><span class="com">// Compute and show the % </span><a href="api/core/ApplicationInitStatus#done" class="code-anchor"><span class="com">done</span></a><span class="com">:</span><span class="pln">
      </span><span class="kwd">const</span><span class="pln"> percentDone </span><span class="pun">=</span><span class="pln"> </span><span class="typ">Math</span><span class="pun">.</span><span class="pln">round</span><span class="pun">(</span><span class="lit">100</span><span class="pln"> </span><span class="pun">*</span><span class="pln"> </span><span class="kwd">event</span><span class="pun">.</span><span class="pln">loaded </span><span class="pun">/</span><span class="pln"> </span><span class="kwd">event</span><span class="pun">.</span><span class="pln">total</span><span class="pun">);</span><span class="pln">
      </span><span class="kwd">return</span><span class="pln"> </span><span class="str">`File "${file.name}" is ${percentDone}% uploaded.`</span><span class="pun">;</span><span class="pln">

    </span><span class="kwd">case</span><span class="pln"> </span><a href="api/common/http/HttpEventType#Response" class="code-anchor"><span class="typ">HttpEventType</span><span class="pun">.</span><span class="typ">Response</span></a><span class="pun">:</span><span class="pln">
      </span><span class="kwd">return</span><span class="pln"> </span><span class="str">`File "${file.name}" was completely uploaded!`</span><span class="pun">;</span><span class="pln">

    </span><span class="kwd">default</span><span class="pun">:</span><span class="pln">
      </span><span class="kwd">return</span><span class="pln"> </span><span class="str">`File "${file.name}" surprising upload event: ${event.type}.`</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></code>
    </pre></aio-code></code-example><div class="alert is-helpful"><p translation-result="on">这个范例应用中并没有一个用来接收上传的文件的真实的服务器。 <code>app/http-interceptors/upload-interceptor.ts</code> 中的 <code>UploadInterceptor</code> 会拦截并短路掉上传请求，改为返回一个带有各个模拟事件的可观察对象。</p><p translation-origin="off">The sample app for this guide doesn't have a server that accepts uploaded files. The <code>UploadInterceptor</code> in <code>app/http-interceptors/upload-interceptor.ts</code> intercepts and short-circuits upload requests by returning an observable of simulated events.</p></div><h2 id="security-xsrf-protection" translation-result="on">安全：XSRF 防护<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#security-xsrf-protection"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="security-xsrf-protection">Security: XSRF Protection<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#security-xsrf-protection"><i class="material-icons">link</i></a></h2><p translation-result="on"><a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery">跨站请求伪造 (XSRF)</a>是一个攻击技术，它能让攻击者假冒一个已认证的用户在你的网站上执行未知的操作。<code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 支持一种<a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery#Cookie-to-Header_Token">通用的机制</a>来防范 XSRF 攻击。当执行 HTTP 请求时，一个拦截器会从 cookie 中读取 XSRF 令牌（默认名字为 <code>XSRF-TOKEN</code>），并且把它设置为一个 HTTP 头 <code>X-XSRF-TOKEN</code>，由于只有运行在你自己的域名下的代码才能读取这个 cookie，因此后端可以确认这个 HTTP 请求真的来自你的客户端应用，而不是攻击者。</p><p translation-origin="off"><a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery">Cross-Site Request Forgery (XSRF)</a> is an attack technique by which the attacker can trick an authenticated user into unknowingly executing actions on your website. <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> supports a <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery#Cookie-to-Header_Token">common mechanism</a> used to prevent XSRF attacks. When performing HTTP requests, an interceptor reads a token from a cookie, by default <code>XSRF-TOKEN</code>, and sets it as an HTTP header, <code>X-XSRF-TOKEN</code>. Since only code that runs on your domain could read the cookie, the backend can be certain that the HTTP request came from your client application and not an attacker.</p><p translation-result="on">默认情况下，拦截器会在所有的修改型请求中（比如 POST 等）把这个 cookie 发送给使用相对 URL 的请求。但不会在 GET/HEAD 请求中发送，也不会发送给使用绝对 URL 的请求。</p><p translation-origin="off">By default, an interceptor sends this cookie on all mutating requests (POST, etc.) to relative URLs but not on GET/HEAD requests or on requests with an absolute URL.</p><p translation-result="on">要获得这种优点，你的服务器需要在页面加载或首个 GET 请求中把一个名叫 <code>XSRF-TOKEN</code> 的令牌写入可被 JavaScript 读到的会话 cookie 中。 而在后续的请求中，服务器可以验证这个 cookie 是否与 HTTP 头 <code>X-XSRF-TOKEN</code> 的值一致，以确保只有运行在你自己域名下的代码才能发起这个请求。这个令牌必须对每个用户都是唯一的，并且必须能被服务器验证，因此不能由客户端自己生成令牌。把这个令牌设置为你的站点认证信息并且加了盐（salt）的摘要，以提升安全性。</p><p translation-origin="off">To take advantage of this, your server needs to set a token in a JavaScript readable session cookie called <code>XSRF-TOKEN</code> on either the page load or the first GET request. On subsequent requests the server can verify that the cookie matches the <code>X-XSRF-TOKEN</code> HTTP header, and therefore be sure that only code running on your domain could have sent the request. The token must be unique for each user and must be verifiable by the server; this prevents the client from making up its own tokens. Set the token to a digest of your site's authentication cookie with a salt for added security.</p><p translation-result="on">为了防止多个 Angular 应用共享同一个域名或子域时出现冲突，要给每个应用分配一个唯一的 cookie 名称。</p><p translation-origin="off">In order to prevent collisions in environments where multiple Angular apps share the same domain or subdomain, give each application a unique cookie name.</p><div class="alert is-important"><p translation-result="on"><em>注意，<code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 支持的只是 XSRF 防护方案的客户端这一半。</em> 你的后端服务必须配置为给页面设置 cookie ，并且要验证请求头，以确保全都是合法的请求。否则，Angular 默认的这种防护措施就会失效。</p><p translation-origin="off"><em>Note that <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> supports only the client half of the XSRF protection scheme.</em> Your backend service must be configured to set the cookie for your page, and to verify that the header is present on all eligible requests. If not, Angular's default protection will be ineffective.</p></div><h3 id="configuring-custom-cookieheader-names" translation-result="on">配置自定义 cookie/header 名称<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#configuring-custom-cookieheader-names"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="configuring-custom-cookieheader-names">Configuring custom cookie/header names<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#configuring-custom-cookieheader-names"><i class="material-icons">link</i></a></h3><p translation-result="on">如果你的后端服务中对 XSRF 令牌的 cookie 或 头使用了不一样的名字，就要使用 <code>HttpClientXsrfModule.withConfig()</code> 来覆盖掉默认值。</p><p translation-origin="off">If your backend service uses different names for the XSRF token cookie or header, use <code><a href="api/common/http/HttpClientXsrfModule#withOptions" class="code-anchor">HttpClientXsrfModule.withOptions()</a></code> to override the defaults.</p><code-example path="http/src/app/app.module.ts" region="xsrf" linenums="false" ng-version="7.0.0"><div style="display:none"><a href="api/core/NgModule#imports" class="code-anchor">imports</a>: [ <a href="api/common/http/HttpClientModule" class="code-anchor">HttpClientModule</a>, HttpClientXsrfModule.withOptions({ cookieName: 'My-Xsrf-Cookie', headerName: 'My-Xsrf-Header', }), ],</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><a href="api/core/NgModule#imports" class="code-anchor"><span class="pln">imports</span></a><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">
  </span><a href="api/common/http/HttpClientModule" class="code-anchor"><span class="typ">HttpClientModule</span></a><span class="pun">,</span><span class="pln">
  </span><span class="typ">HttpClientXsrfModule</span><span class="pun">.</span><span class="pln">withOptions</span><span class="pun">({</span><span class="pln">
    cookieName</span><span class="pun">:</span><span class="pln"> </span><span class="str">'My-Xsrf-Cookie'</span><span class="pun">,</span><span class="pln">
    headerName</span><span class="pun">:</span><span class="pln"> </span><span class="str">'My-Xsrf-Header'</span><span class="pun">,</span><span class="pln">
  </span><span class="pun">}),</span><span class="pln">
</span><span class="pun">],</span></code>
    </pre></aio-code></code-example><h2 id="testing-http-requests" translation-result="on">测试 HTTP 请求<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#testing-http-requests"><i class="material-icons">link</i></a></h2><h2 translation-origin="off" id="testing-http-requests">Testing HTTP requests<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#testing-http-requests"><i class="material-icons">link</i></a></h2><p translation-result="on">如同所有的外部依赖一样，HTTP 后端也需要在良好的测试实践中被 Mock 掉。<code>@angular/common/<a href="api/common/http" class="code-anchor">http</a></code> 提供了一个测试库 <code>@angular/common/<a href="api/common/http" class="code-anchor">http</a>/testing</code>，它让你可以直截了当的进行这种 Mock 。</p><p translation-origin="off">Like any external dependency, the HTTP backend needs to be mocked so your tests can simulate interaction with a remote server. The <code>@angular/common/<a href="api/common/http" class="code-anchor">http</a>/testing</code> library makes setting up such mocking straightforward.</p><h3 id="mocking-philosophy" translation-result="on">Mock 方法论<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#mocking-philosophy"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="mocking-philosophy">Mocking philosophy<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#mocking-philosophy"><i class="material-icons">link</i></a></h3><p translation-result="on">Angular 的 HTTP 测试库是专为其中的测试模式而设计的。在这种模式下，会首先在应用中执行代码并发起请求。</p><p translation-origin="off">Angular's HTTP testing library is designed for a pattern of testing wherein the app executes code and makes requests first.</p><p translation-result="on">然后，每个测试会期待发起或未发起过某个请求，对这些请求进行断言， 最终对每个所预期的请求进行刷新（flush）来对这些请求提供响应。</p><p translation-origin="off">Then a test expects that certain requests have or have not been made, performs assertions against those requests, and finally provide responses by "flushing" each expected request.</p><p translation-result="on">最终，测试可能会验证这个应用不曾发起过非预期的请求。</p><p translation-origin="off">At the end, tests may verify that the app has made no unexpected requests.</p><div class="alert is-helpful"><p translation-result="on">你可以到在线编程环境中运行<live-example stackblitz="specs" ng-version="7.0.0"><span style="display:none">这些范例测试</span><span><span class="ng-star-inserted"><a target="_blank" href="generated/live-examples/http/specs.stackblitz.html" title="这些范例测试">这些范例测试</a><span class="ng-star-inserted"> / <a download="" title="下载范例" href="generated/zips/http/specs.http.zip">下载范例</a></span></span></span></live-example>。</p><p translation-origin="off">You can run<live-example stackblitz="specs" ng-version="7.0.0"><span style="display:none">these sample tests</span><span><span class="ng-star-inserted"><a target="_blank" href="generated/live-examples/http/specs.stackblitz.html" title="these sample tests">these sample tests</a><span class="ng-star-inserted"> / <a download="" title="下载范例" href="generated/zips/http/specs.http.zip">下载范例</a></span></span></span></live-example>in a live coding environment.</p><p translation-result="on">本章所讲的这些测试位于 <code>src/testing/http-client.spec.ts</code> 中。 在 <code>src/app/heroes/heroes.service.spec.ts</code> 中还有一些测试，用于测试那些调用了 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 的数据服务。</p><p translation-origin="off">The tests described in this guide are in <code>src/testing/http-client.spec.ts</code>. There are also tests of an application data service that call <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> in <code>src/app/heroes/heroes.service.spec.ts</code>.</p></div><h3 id="setup-1" translation-result="on">搭建环境<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#setup-1"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="setup-1">Setup<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#setup-1"><i class="material-icons">link</i></a></h3><p translation-result="on">要开始测试那些通过 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 发起的请求，就要导入 <code><a href="api/common/http/testing/HttpClientTestingModule" class="code-anchor">HttpClientTestingModule</a></code> 模块，并把它加到你的 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 设置里去，代码如下：</p><p translation-origin="off">To begin testing calls to <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code>, import the <code><a href="api/common/http/testing/HttpClientTestingModule" class="code-anchor">HttpClientTestingModule</a></code> and the mocking controller, <code><a href="api/common/http/testing/HttpTestingController" class="code-anchor">HttpTestingController</a></code>, along with the other symbols your tests require.</p><code-example path="http/src/testing/http-client.spec.ts" region="imports" header="app/testing/http-client.spec.ts (imports)" linenums="false" ng-version="7.0.0"><div style="display:none">// <a href="api/http/Http" class="code-anchor">Http</a> testing module and mocking controller import { <a href="api/common/http/testing/HttpClientTestingModule" class="code-anchor">HttpClientTestingModule</a>, <a href="api/common/http/testing/HttpTestingController" class="code-anchor">HttpTestingController</a> } from '@angular/common/<a href="api/common/http" class="code-anchor">http</a>/testing'; // <a href="api/common/Plural#Other" class="code-anchor">Other</a> <a href="api/core/NgModule#imports" class="code-anchor">imports</a> import { <a href="api/core/testing/TestBed" class="code-anchor">TestBed</a> } from '@angular/core/testing'; import { <a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a>, <a href="api/common/http/HttpErrorResponse" class="code-anchor">HttpErrorResponse</a> } from '@angular/common/<a href="api/common/http" class="code-anchor">http</a>';</div><header class="ng-star-inserted">app/testing/http-client.spec.ts (imports)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/testing/http-client.spec.ts (imports)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// </span><a href="api/http/Http" class="code-anchor"><span class="com">Http</span></a><span class="com"> testing module and mocking controller</span><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/common/http/testing/HttpClientTestingModule" class="code-anchor"><span class="typ">HttpClientTestingModule</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/common/http/testing/HttpTestingController" class="code-anchor"><span class="typ">HttpTestingController</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/common/</span><a href="api/common/http" class="code-anchor"><span class="str">http</span></a><span class="str">/testing'</span><span class="pun">;</span><span class="pln">

</span><span class="com">// </span><a href="api/common/Plural#Other" class="code-anchor"><span class="com">Other</span></a><span class="com"> </span><a href="api/core/NgModule#imports" class="code-anchor"><span class="com">imports</span></a><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/core/testing/TestBed" class="code-anchor"><span class="typ">TestBed</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/core/testing'</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">import</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><a href="api/common/http/HttpClient" class="code-anchor"><span class="typ">HttpClient</span></a><span class="pun">,</span><span class="pln"> </span><a href="api/common/http/HttpErrorResponse" class="code-anchor"><span class="typ">HttpErrorResponse</span></a><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">from</span><span class="pln"> </span><span class="str">'@angular/common/</span><a href="api/common/http" class="code-anchor"><span class="str">http</span></a><span class="str">'</span><span class="pun">;</span></code>
    </pre></aio-code></code-example><p translation-result="on">然后把 <code>HTTPClientTestingModule</code> 添加到 <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> 中，并继续设置<em>被测服务</em>。</p><p translation-origin="off">Then add the <code><a href="api/common/http/testing/HttpClientTestingModule" class="code-anchor">HttpClientTestingModule</a></code> to the <code><a href="api/core/testing/TestBed" class="code-anchor">TestBed</a></code> and continue with the setup of the <em>service-under-test</em>.</p><code-example path="http/src/testing/http-client.spec.ts" region="setup" header="app/testing/http-client.spec.ts(setup)" linenums="false" ng-version="7.0.0"><div style="display:none">describe('<a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a> testing', () =&gt; { let httpClient: <a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a>; let httpTestingController: <a href="api/common/http/testing/HttpTestingController" class="code-anchor">HttpTestingController</a>; beforeEach(() =&gt; { TestBed.configureTestingModule({ <a href="api/core/NgModule#imports" class="code-anchor">imports</a>: [ <a href="api/common/http/testing/HttpClientTestingModule" class="code-anchor">HttpClientTestingModule</a> ] }); // <a href="api/core/Inject" class="code-anchor">Inject</a> the <a href="api/common/http" class="code-anchor">http</a> service and test controller for each test httpClient = TestBed.get(<a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a>); httpTestingController = TestBed.get(<a href="api/common/http/testing/HttpTestingController" class="code-anchor">HttpTestingController</a>); }); /// Tests begin /// });</div><header class="ng-star-inserted">app/testing/http-client.spec.ts(setup)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/testing/http-client.spec.ts(setup)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">describe</span><span class="pun">(</span><span class="str">'</span><a href="api/common/http/HttpClient" class="code-anchor"><span class="str">HttpClient</span></a><span class="str"> testing'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> httpClient</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpClient" class="code-anchor"><span class="typ">HttpClient</span></a><span class="pun">;</span><span class="pln">
  </span><span class="kwd">let</span><span class="pln"> httpTestingController</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/testing/HttpTestingController" class="code-anchor"><span class="typ">HttpTestingController</span></a><span class="pun">;</span><span class="pln">

  beforeEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="typ">TestBed</span><span class="pun">.</span><span class="pln">configureTestingModule</span><span class="pun">({</span><span class="pln">
      </span><a href="api/core/NgModule#imports" class="code-anchor"><span class="pln">imports</span></a><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln"> </span><a href="api/common/http/testing/HttpClientTestingModule" class="code-anchor"><span class="typ">HttpClientTestingModule</span></a><span class="pln"> </span><span class="pun">]</span><span class="pln">
    </span><span class="pun">});</span><span class="pln">

    </span><span class="com">// </span><a href="api/core/Inject" class="code-anchor"><span class="com">Inject</span></a><span class="com"> the </span><a href="api/common/http" class="code-anchor"><span class="com">http</span></a><span class="com"> service and test controller for each test</span><span class="pln">
    httpClient </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">(</span><a href="api/common/http/HttpClient" class="code-anchor"><span class="typ">HttpClient</span></a><span class="pun">);</span><span class="pln">
    httpTestingController </span><span class="pun">=</span><span class="pln"> </span><span class="typ">TestBed</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">(</span><a href="api/common/http/testing/HttpTestingController" class="code-anchor"><span class="typ">HttpTestingController</span></a><span class="pun">);</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">
  </span><span class="com">/// Tests begin ///</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">现在，在测试中发起的这些请求会发给这些测试用的后端（testing backend），而不是标准的后端。</p><p translation-origin="off">Now requests made in the course of your tests will hit the testing backend instead of the normal backend.</p><p translation-result="on">这种设置还会调用 <code>TestBed.get()</code>，来获取注入的 <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> 服务和模拟对象的控制器 <code><a href="api/common/http/testing/HttpTestingController" class="code-anchor">HttpTestingController</a></code>，以便在测试期间引用它们。</p><p translation-origin="off">This setup also calls <code>TestBed.get()</code> to inject the <code><a href="api/common/http/HttpClient" class="code-anchor">HttpClient</a></code> service and the mocking controller so they can be referenced during the tests.</p><h3 id="expecting-and-answering-requests" translation-result="on">期待并回复请求<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#expecting-and-answering-requests"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="expecting-and-answering-requests">Expecting and answering requests<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#expecting-and-answering-requests"><i class="material-icons">link</i></a></h3><p translation-result="on">现在，你就可以编写测试，等待 GET 请求并给出模拟响应。</p><p translation-origin="off">Now you can write a test that expects a GET Request to occur and provides a mock response.</p><code-example path="http/src/testing/http-client.spec.ts" region="get-test" header="app/testing/http-client.spec.ts(httpClient.get)" linenums="false" ng-version="7.0.0"><div style="display:none">it('can test HttpClient.get', () =&gt; { const testData: <a href="api/router/Data" class="code-anchor">Data</a> = {name: 'Test <a href="api/router/Data" class="code-anchor">Data</a>'}; // Make an HTTP GET request httpClient.get&lt;<a href="api/router/Data" class="code-anchor">Data</a>&gt;(testUrl) .subscribe(data =&gt; // When observable resolves, result should match test data expect(data).toEqual(testData) ); // The following `expectOne()` will match the request's URL. // If no requests or <a href="api/forms/SelectMultipleControlValueAccessor" class="code-anchor">multiple</a> requests matched that <a href="api/core/SecurityContext#URL" class="code-anchor">URL</a> // `expectOne()` would throw. const req = httpTestingController.expectOne('/data'); // Assert that the request is <a href="api/router/RouterLinkWithHref" class="code-anchor">a</a> GET. expect(req.request.method).toEqual('GET'); // Respond with mock data, causing Observable to resolve. // Subscribe callback asserts that correct data was returned. req.flush(testData); // Finally, assert that there are no outstanding requests. httpTestingController.verify(); });</div><header class="ng-star-inserted">app/testing/http-client.spec.ts(httpClient.get)</header><aio-code class="headed-code"><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="Copy code snippet from app/testing/http-client.spec.ts(httpClient.get)">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'can test HttpClient.get'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> testData</span><span class="pun">:</span><span class="pln"> </span><a href="api/router/Data" class="code-anchor"><span class="typ">Data</span></a><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="pun">{</span><span class="pln">name</span><span class="pun">:</span><span class="pln"> </span><span class="str">'Test </span><a href="api/router/Data" class="code-anchor"><span class="str">Data</span></a><span class="str">'</span><span class="pun">};</span><span class="pln">

  </span><span class="com">// Make an HTTP GET request</span><span class="pln">
  httpClient</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">&lt;</span><a href="api/router/Data" class="code-anchor"><span class="typ">Data</span></a><span class="pun">&gt;(</span><span class="pln">testUrl</span><span class="pun">)</span><span class="pln">
    </span><span class="pun">.</span><span class="pln">subscribe</span><span class="pun">(</span><span class="pln">data </span><span class="pun">=&gt;</span><span class="pln">
      </span><span class="com">// When observable resolves, result should match test data</span><span class="pln">
      expect</span><span class="pun">(</span><span class="pln">data</span><span class="pun">).</span><span class="pln">toEqual</span><span class="pun">(</span><span class="pln">testData</span><span class="pun">)</span><span class="pln">
    </span><span class="pun">);</span><span class="pln">

  </span><span class="com">// The following `expectOne()` will match the request's URL.</span><span class="pln">
  </span><span class="com">// If no requests or </span><a href="api/forms/SelectMultipleControlValueAccessor" class="code-anchor"><span class="com">multiple</span></a><span class="com"> requests matched that </span><a href="api/core/SecurityContext#URL" class="code-anchor"><span class="com">URL</span></a><span class="pln">
  </span><span class="com">// `expectOne()` would throw.</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> req </span><span class="pun">=</span><span class="pln"> httpTestingController</span><span class="pun">.</span><span class="pln">expectOne</span><span class="pun">(</span><span class="str">'/data'</span><span class="pun">);</span><span class="pln">

  </span><span class="com">// Assert that the request is </span><a href="api/router/RouterLinkWithHref" class="code-anchor"><span class="com">a</span></a><span class="com"> GET.</span><span class="pln">
  expect</span><span class="pun">(</span><span class="pln">req</span><span class="pun">.</span><span class="pln">request</span><span class="pun">.</span><span class="pln">method</span><span class="pun">).</span><span class="pln">toEqual</span><span class="pun">(</span><span class="str">'GET'</span><span class="pun">);</span><span class="pln">

  </span><span class="com">// Respond with mock data, causing Observable to resolve.</span><span class="pln">
  </span><span class="com">// Subscribe callback asserts that correct data was returned.</span><span class="pln">
  req</span><span class="pun">.</span><span class="pln">flush</span><span class="pun">(</span><span class="pln">testData</span><span class="pun">);</span><span class="pln">

  </span><span class="com">// Finally, assert that there are no outstanding requests.</span><span class="pln">
  httpTestingController</span><span class="pun">.</span><span class="pln">verify</span><span class="pun">();</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">最后一步，验证没有发起过预期之外的请求，足够通用，因此你可以把它移到 <code>afterEach()</code> 中：</p><p translation-origin="off">The last step, verifying that no requests remain outstanding, is common enough for you to move it into an <code>afterEach()</code> step:</p><code-example path="http/src/testing/http-client.spec.ts" region="afterEach" linenums="false" ng-version="7.0.0"><div style="display:none">afterEach(() =&gt; { // After every test, assert that there are no more pending requests. httpTestingController.verify(); });</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">afterEach</span><span class="pun">(()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="com">// After every test, assert that there are no more pending requests.</span><span class="pln">
  httpTestingController</span><span class="pun">.</span><span class="pln">verify</span><span class="pun">();</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><h4 id="custom-request-expectations" translation-result="on">自定义对请求的预期<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#custom-request-expectations"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="custom-request-expectations">Custom request expectations<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#custom-request-expectations"><i class="material-icons">link</i></a></h4><p translation-result="on">如果仅根据 URL 匹配还不够，你还可以自行实现匹配函数。 比如，你可以验证外发的请求是否带有某个认证头：</p><p translation-origin="off">If matching by URL isn't sufficient, it's possible to implement your own matching function. For example, you could look for an outgoing request that has an authorization header:</p><code-example path="http/src/testing/http-client.spec.ts" region="predicate" linenums="false" ng-version="7.0.0"><div style="display:none">// Expect one request with an authorization header const req = httpTestingController.expectOne( req =&gt; req.headers.has('Authorization') );</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// Expect one request with an authorization header</span><span class="pln">
</span><span class="kwd">const</span><span class="pln"> req </span><span class="pun">=</span><span class="pln"> httpTestingController</span><span class="pun">.</span><span class="pln">expectOne</span><span class="pun">(</span><span class="pln">
  req </span><span class="pun">=&gt;</span><span class="pln"> req</span><span class="pun">.</span><span class="pln">headers</span><span class="pun">.</span><span class="pln">has</span><span class="pun">(</span><span class="str">'Authorization'</span><span class="pun">)</span><span class="pln">
</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><p translation-result="on">像前面的 <code>expectOne()</code> 测试一样，如果零或两个以上的请求满足了这个断言，它就会抛出异常。</p><p translation-origin="off">As with the previous <code>expectOne()</code>, the test will fail if 0 or 2+ requests satisfy this predicate.</p><h4 id="handling-more-than-one-request" translation-result="on">处理一个以上的请求<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#handling-more-than-one-request"><i class="material-icons">link</i></a></h4><h4 translation-origin="off" id="handling-more-than-one-request">Handling more than one request<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#handling-more-than-one-request"><i class="material-icons">link</i></a></h4><p translation-result="on">如果你需要在测试中对重复的请求进行响应，可以使用 <code>match()</code> API 来代替 <code>expectOne()</code>，它的参数不变，但会返回一个与这些请求相匹配的数组。一旦返回，这些请求就会从将来要匹配的列表中移除，你要自己验证和刷新（flush）它。</p><p translation-origin="off">If you need to respond to duplicate requests in your test, use the <code>match()</code> API instead of <code>expectOne()</code>. It takes the same arguments but returns an array of matching requests. Once returned, these requests are removed from future matching and you are responsible for flushing and verifying them.</p><code-example path="http/src/testing/http-client.spec.ts" region="multi-request" linenums="false" ng-version="7.0.0"><div style="display:none">// get all pending requests that match the given <a href="api/core/SecurityContext#URL" class="code-anchor">URL</a> const requests = httpTestingController.match(testUrl); expect(requests.length).toEqual(3); // Respond to each request with different results requests[0].flush([]); requests[1].flush([testData[0]]); requests[2].flush(testData);</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="com">// get all pending requests that match the given </span><a href="api/core/SecurityContext#URL" class="code-anchor"><span class="com">URL</span></a><span class="pln">
</span><span class="kwd">const</span><span class="pln"> requests </span><span class="pun">=</span><span class="pln"> httpTestingController</span><span class="pun">.</span><span class="pln">match</span><span class="pun">(</span><span class="pln">testUrl</span><span class="pun">);</span><span class="pln">
expect</span><span class="pun">(</span><span class="pln">requests</span><span class="pun">.</span><span class="pln">length</span><span class="pun">).</span><span class="pln">toEqual</span><span class="pun">(</span><span class="lit">3</span><span class="pun">);</span><span class="pln">

</span><span class="com">// Respond to each request with different results</span><span class="pln">
requests</span><span class="pun">[</span><span class="lit">0</span><span class="pun">].</span><span class="pln">flush</span><span class="pun">([]);</span><span class="pln">
requests</span><span class="pun">[</span><span class="lit">1</span><span class="pun">].</span><span class="pln">flush</span><span class="pun">([</span><span class="pln">testData</span><span class="pun">[</span><span class="lit">0</span><span class="pun">]]);</span><span class="pln">
requests</span><span class="pun">[</span><span class="lit">2</span><span class="pun">].</span><span class="pln">flush</span><span class="pun">(</span><span class="pln">testData</span><span class="pun">);</span></code>
    </pre></aio-code></code-example><h3 id="testing-for-errors" translation-result="on">测试对错误的预期<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#testing-for-errors"><i class="material-icons">link</i></a></h3><h3 translation-origin="off" id="testing-for-errors">Testing for errors<a title="Link to this heading" class="header-link" aria-hidden="true" href="guide/http#testing-for-errors"><i class="material-icons">link</i></a></h3><p translation-result="on">你还要测试应用对于 HTTP 请求失败时的防护。</p><p translation-origin="off">You should test the app's defenses against HTTP requests that fail.</p><p translation-result="on">调用 <code>request.flush()</code> 并传入一个错误信息，如下所示：</p><p translation-origin="off">Call <code>request.flush()</code> with an error message, as seen in the following example.</p><code-example path="http/src/testing/http-client.spec.ts" region="404" linenums="false" ng-version="7.0.0"><div style="display:none">it('can test for 404 error', () =&gt; { const emsg = 'deliberate 404 error'; httpClient.get&lt;<a href="api/router/Data" class="code-anchor">Data</a>[]&gt;(testUrl).subscribe( data =&gt; fail('should have failed with the 404 error'), (error: <a href="api/common/http/HttpErrorResponse" class="code-anchor">HttpErrorResponse</a>) =&gt; { expect(error.status).toEqual(404, 'status'); expect(error.error).toEqual(emsg, '<a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a>'); } ); const req = httpTestingController.expectOne(testUrl); // Respond with mock error req.flush(emsg, { status: 404, statusText: 'Not Found' }); });</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'can test for 404 error'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> emsg </span><span class="pun">=</span><span class="pln"> </span><span class="str">'deliberate 404 error'</span><span class="pun">;</span><span class="pln">

  httpClient</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">&lt;</span><a href="api/router/Data" class="code-anchor"><span class="typ">Data</span></a><span class="pun">[]&gt;(</span><span class="pln">testUrl</span><span class="pun">).</span><span class="pln">subscribe</span><span class="pun">(</span><span class="pln">
    data </span><span class="pun">=&gt;</span><span class="pln"> fail</span><span class="pun">(</span><span class="str">'should have failed with the 404 error'</span><span class="pun">),</span><span class="pln">
    </span><span class="pun">(</span><span class="pln">error</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpErrorResponse" class="code-anchor"><span class="typ">HttpErrorResponse</span></a><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
      expect</span><span class="pun">(</span><span class="pln">error</span><span class="pun">.</span><span class="pln">status</span><span class="pun">).</span><span class="pln">toEqual</span><span class="pun">(</span><span class="lit">404</span><span class="pun">,</span><span class="pln"> </span><span class="str">'status'</span><span class="pun">);</span><span class="pln">
      expect</span><span class="pun">(</span><span class="pln">error</span><span class="pun">.</span><span class="pln">error</span><span class="pun">).</span><span class="pln">toEqual</span><span class="pun">(</span><span class="pln">emsg</span><span class="pun">,</span><span class="pln"> </span><span class="str">'</span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="str">message</span></a><span class="str">'</span><span class="pun">);</span><span class="pln">
    </span><span class="pun">}</span><span class="pln">
  </span><span class="pun">);</span><span class="pln">

  </span><span class="kwd">const</span><span class="pln"> req </span><span class="pun">=</span><span class="pln"> httpTestingController</span><span class="pun">.</span><span class="pln">expectOne</span><span class="pun">(</span><span class="pln">testUrl</span><span class="pun">);</span><span class="pln">

  </span><span class="com">// Respond with mock error</span><span class="pln">
  req</span><span class="pun">.</span><span class="pln">flush</span><span class="pun">(</span><span class="pln">emsg</span><span class="pun">,</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> status</span><span class="pun">:</span><span class="pln"> </span><span class="lit">404</span><span class="pun">,</span><span class="pln"> statusText</span><span class="pun">:</span><span class="pln"> </span><span class="str">'Not Found'</span><span class="pln"> </span><span class="pun">});</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example><p translation-result="on">另外，你还可以使用 <code>ErrorEvent</code> 来调用 <code>request.error()</code>.</p><p translation-origin="off">Alternatively, you can call <code>request.error()</code> with an <code>ErrorEvent</code>.</p><code-example path="http/src/testing/http-client.spec.ts" region="network-error" linenums="false" ng-version="7.0.0"><div style="display:none">it('can test for network error', () =&gt; { const emsg = 'simulated network error'; httpClient.get&lt;<a href="api/router/Data" class="code-anchor">Data</a>[]&gt;(testUrl).subscribe( data =&gt; fail('should have failed with the network error'), (error: <a href="api/common/http/HttpErrorResponse" class="code-anchor">HttpErrorResponse</a>) =&gt; { expect(error.error.message).toEqual(emsg, '<a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a>'); } ); const req = httpTestingController.expectOne(testUrl); // Create mock ErrorEvent, raised when something goes wrong at the network level. // <a href="api/http/Connection" class="code-anchor">Connection</a> timeout, DNS error, offline, etc const mockError = new ErrorEvent('Network error', { <a href="api/common/http/HttpErrorResponse#message" class="code-anchor">message</a>: emsg, }); // Respond with mock error req.error(mockError); });</div><aio-code><pre class="prettyprint lang-">      <button class="material-icons copy-button no-print ng-star-inserted" title="Copy code snippet" aria-label="">
        <span aria-hidden="true">content_copy</span>
      </button>
      <code class="animated fadeIn"><span class="pln">it</span><span class="pun">(</span><span class="str">'can test for network error'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> emsg </span><span class="pun">=</span><span class="pln"> </span><span class="str">'simulated network error'</span><span class="pun">;</span><span class="pln">

  httpClient</span><span class="pun">.</span><span class="kwd">get</span><span class="pun">&lt;</span><a href="api/router/Data" class="code-anchor"><span class="typ">Data</span></a><span class="pun">[]&gt;(</span><span class="pln">testUrl</span><span class="pun">).</span><span class="pln">subscribe</span><span class="pun">(</span><span class="pln">
    data </span><span class="pun">=&gt;</span><span class="pln"> fail</span><span class="pun">(</span><span class="str">'should have failed with the network error'</span><span class="pun">),</span><span class="pln">
    </span><span class="pun">(</span><span class="pln">error</span><span class="pun">:</span><span class="pln"> </span><a href="api/common/http/HttpErrorResponse" class="code-anchor"><span class="typ">HttpErrorResponse</span></a><span class="pun">)</span><span class="pln"> </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
      expect</span><span class="pun">(</span><span class="pln">error</span><span class="pun">.</span><span class="pln">error</span><span class="pun">.</span><span class="pln">message</span><span class="pun">).</span><span class="pln">toEqual</span><span class="pun">(</span><span class="pln">emsg</span><span class="pun">,</span><span class="pln"> </span><span class="str">'</span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="str">message</span></a><span class="str">'</span><span class="pun">);</span><span class="pln">
    </span><span class="pun">}</span><span class="pln">
  </span><span class="pun">);</span><span class="pln">

  </span><span class="kwd">const</span><span class="pln"> req </span><span class="pun">=</span><span class="pln"> httpTestingController</span><span class="pun">.</span><span class="pln">expectOne</span><span class="pun">(</span><span class="pln">testUrl</span><span class="pun">);</span><span class="pln">

  </span><span class="com">// Create mock ErrorEvent, raised when something goes wrong at the network level.</span><span class="pln">
  </span><span class="com">// </span><a href="api/http/Connection" class="code-anchor"><span class="com">Connection</span></a><span class="com"> timeout, DNS error, offline, etc</span><span class="pln">
  </span><span class="kwd">const</span><span class="pln"> mockError </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">ErrorEvent</span><span class="pun">(</span><span class="str">'Network error'</span><span class="pun">,</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><a href="api/common/http/HttpErrorResponse#message" class="code-anchor"><span class="pln">message</span></a><span class="pun">:</span><span class="pln"> emsg</span><span class="pun">,</span><span class="pln">
  </span><span class="pun">});</span><span class="pln">

  </span><span class="com">// Respond with mock error</span><span class="pln">
  req</span><span class="pun">.</span><span class="pln">error</span><span class="pun">(</span><span class="pln">mockError</span><span class="pun">);</span><span class="pln">
</span><span class="pun">});</span></code>
    </pre></aio-code></code-example></div></div></aio-doc-viewer></main></mat-sidenav-content></mat-sidenav-container><div class="toc-container no-print ng-star-inserted"><aio-lazy-ce selector="aio-toc"><aio-toc ng-version="7.0.0"><div class="toc-inner no-print collapsed ng-star-inserted"><ul class="toc-list"><li title="HttpClientlink" class="h1 ng-star-inserted active"><a href="guide/http#httpclient">HttpClient</a></li><li title="准备工作link" class="h2 ng-star-inserted"><a href="guide/http#setup">准备工作</a></li><li title="获取 JSON 数据link" class="h2 ng-star-inserted"><a href="guide/http#getting-json-data">获取 JSON 数据</a></li><li title="为什么要写服务link" class="h3 ng-star-inserted"><a href="guide/http#why-write-a-service">为什么要写服务</a></li><li title="带类型检查的响应link" class="h3 ng-star-inserted"><a href="guide/http#type-checking-the-response">带类型检查的响应</a></li><li title="读取完整的响应体link" class="h3 ng-star-inserted"><a href="guide/http#reading-the-full-response">读取完整的响应体</a></li><li title="错误处理link" class="h2 ng-star-inserted"><a href="guide/http#error-handling">错误处理</a></li><li title="获取错误详情link" class="h3 ng-star-inserted"><a href="guide/http#getting-error-details">获取错误详情</a></li><li title="retry()link" class="h3 ng-star-inserted"><a href="guide/http#retry"><code>retry()</code></a></li><li title="可观察对象 (Observable) 与操作符 (operator)link" class="h2 ng-star-inserted"><a href="guide/http#observables-and-operators">可观察对象 (Observable) 与操作符 (operator)</a></li><li title="请求非 JSON 格式的数据link" class="h2 ng-star-inserted"><a href="guide/http#requesting-non-json-data">请求非 JSON 格式的数据</a></li><li title="把数据发送到服务器link" class="h2 ng-star-inserted"><a href="guide/http#sending-data-to-the-server">把数据发送到服务器</a></li><li title="添加请求头link" class="h3 ng-star-inserted"><a href="guide/http#adding-headers">添加请求头</a></li><li title="发起一个 POST 请求link" class="h3 ng-star-inserted"><a href="guide/http#making-a-post-request">发起一个 POST 请求</a></li><li title="发起 DELETE 请求link" class="h3 ng-star-inserted"><a href="guide/http#making-a-delete-request">发起 <code>DELETE</code> 请求</a></li><li title="发起 PUT 请求link" class="h3 ng-star-inserted"><a href="guide/http#making-a-put-request">发起 PUT 请求</a></li><li title="高级用法link" class="h2 ng-star-inserted"><a href="guide/http#advanced-usage">高级用法</a></li><li title="配置请求link" class="h3 ng-star-inserted"><a href="guide/http#configuring-the-request">配置请求</a></li><li title="请求的防抖（debounce）link" class="h3 ng-star-inserted"><a href="guide/http#debouncing-requests">请求的防抖（debounce）</a></li><li title="拦截请求和响应link" class="h3 ng-star-inserted"><a href="guide/http#intercepting-requests-and-responses">拦截请求和响应</a></li><li title="监听进度事件link" class="h3 ng-star-inserted"><a href="guide/http#listening-to-progress-events">监听进度事件</a></li><li title="安全：XSRF 防护link" class="h2 ng-star-inserted"><a href="guide/http#security-xsrf-protection">安全：XSRF 防护</a></li><li title="配置自定义 cookie/header 名称link" class="h3 ng-star-inserted"><a href="guide/http#configuring-custom-cookieheader-names">配置自定义 cookie/header 名称</a></li><li title="测试 HTTP 请求link" class="h2 ng-star-inserted"><a href="guide/http#testing-http-requests">测试 HTTP 请求</a></li><li title="Mock 方法论link" class="h3 ng-star-inserted"><a href="guide/http#mocking-philosophy">Mock 方法论</a></li><li title="搭建环境link" class="h3 ng-star-inserted"><a href="guide/http#setup-1">搭建环境</a></li><li title="期待并回复请求link" class="h3 ng-star-inserted"><a href="guide/http#expecting-and-answering-requests">期待并回复请求</a></li><li title="测试对错误的预期link" class="h3 ng-star-inserted"><a href="guide/http#testing-for-errors">测试对错误的预期</a></li></ul></div></aio-toc></aio-lazy-ce></div><footer class="no-print"><aio-footer><div class="grid-fluid"><div class="footer-block ng-star-inserted"><h3>资源</h3><ul><li class="ng-star-inserted"><a class="link" href="about" title="Angular 贡献者。">关于</a></li><li class="ng-star-inserted"><a class="link" href="resources" title="网络上的 Angular 工具、培训、博客等">资源列表</a></li><li class="ng-star-inserted"><a class="link" href="presskit" title="我们的联系方式、LOGO 和品牌">宣传资料</a></li><li class="ng-star-inserted"><a class="link" href="https://blog.angular.io/" title="Angular 官方博客">博客</a></li></ul></div><div class="footer-block ng-star-inserted"><h3>帮助</h3><ul><li class="ng-star-inserted"><a class="link" href="https://stackoverflow.com/questions/tagged/angular" title="Stack Overflow: 这里的社区会回答你关于 Angular 的技术问题">Stack Overflow</a></li><li class="ng-star-inserted"><a class="link" href="https://gitter.im/angular/angular" title="和老鸟聊 Angular">Gitter</a></li><li class="ng-star-inserted"><a class="link" href="https://github.com/angular/angular/issues" title="在 github 上报告问题和建议。">报告问题</a></li><li class="ng-star-inserted"><a class="link" href="https://github.com/angular/code-of-conduct/blob/master/CODE_OF_CONDUCT.md" title="让我们彼此尊重">行为规范</a></li></ul></div><div class="footer-block ng-star-inserted"><h3>社区</h3><ul><li class="ng-star-inserted"><a class="link" href="events" title="Post issues and suggestions on github.">活动</a></li><li class="ng-star-inserted"><a class="link" href="http://www.meetup.com/topics/angularjs/" title="参加聚会，向别的开发人员学习">聚会</a></li><li class="ng-star-inserted"><a class="link" href="https://twitter.com/angular" title="Twitter">Twitter</a></li><li class="ng-star-inserted"><a class="link" href="https://github.com/angular/angular" title="GitHub">GitHub</a></li><li class="ng-star-inserted"><a class="link" href="contribute" title="向 Angular 做贡献">做贡献</a></li></ul></div><div class="footer-block ng-star-inserted"><h3>多语言</h3><ul><li class="ng-star-inserted"><a class="link" href="https://angular.io/" title="English Version.">English Version</a></li><li class="ng-star-inserted"><a class="link" href="https://angular.jp/" title="日本語版">日本語版</a></li><li class="ng-star-inserted"><a class="link" href="https://angular.kr/" title="한국어">한국어</a></li></ul></div></div><p>Super-powered by Google ©2010-2019. 代码授权方式：<a href="license" title="License text">MIT-style License</a>. 文档授权方式：<a href="http://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>.</p><p>当前版本：8.0.0-build.95+sha.43aadf1.</p></aio-footer></footer><mat-icon class="cdk-visually-hidden mat-icon material-icons ng-star-inserted" role="img" aria-hidden="true">&nbsp;</mat-icon></aio-shell><noscript><div class="background-sky hero"></div><section id="intro" style="text-shadow:1px 1px #1976d2"><div class="hero-logo"><img src="assets/images/logos/angular/angular.svg" width="250" height="250" alt="Angular"></div><div class="homepage-container"><div class="hero-headline">一套框架，多种平台<br>移动 &amp; 桌面</div></div></section><h2 style="color:red;margin-top:40px;position:relative;text-align:center;text-shadow:1px 1px #fafafa"><b><i>该网站需要浏览器支持 JavaScript</i></b></h2></noscript><script src="runtime.fa3355727d5250409e08.js"></script><script src="polyfills.a2efc1c1a62312ff1f80.js"></script><script src="main.02884fe4cde5ede2ec4e.js"></script><div class="cdk-live-announcer-element cdk-visually-hidden" aria-atomic="true" aria-live="polite"></div></body></html>